SlideShare uma empresa Scribd logo
1 de 8
Baixar para ler offline
DataFest Theano tutorial
September 20, 2015
1 Introduction
This is a basic theano tutorial, presented at the Moscow Data Fest: http://www.meetup.com/Moscow-Data-
Fest/events/224856462/.
You can find the code here: https://github.com/dudevil/datafest-theano-tutorial/.
1.1 Baby steps
In [1]: import numpy as np
import theano
import theano.tensor as T
%pylab inline
figsize(8, 6)
Populating the interactive namespace from numpy and matplotlib
In [18]: # declare theano variable
a = theano.tensor.lscalar()
#a = theano.tensor.vector()
expression = 1 + 2 * a + a ** 2
f = theano.function(
[a],
expression)
In [7]: #f(0)
result = f(np.arange(-10, 10))
result
Out[7]: array([ 81., 64., 49., 36., 25., 16., 9., 4., 1.,
0., 1., 4., 9., 16., 25., 36., 49., 64.,
81., 100.])
In [8]: plot(np.arange(-10, 10), result, c=’m’, linewidth=2.)
grid()
1
In [9]: # shared variables represent internal state
state = theano.shared(0)
i = T.iscalar(’i’)
accumulator = theano.function([i],
state,
updates=[(state, state+i)])
In [14]: accumulator(5)
Out[14]: array(20)
In [15]: state.set_value(-15)
print state.get_value()
-15
In [19]: state.set_value(0)
f = theano.function(
[i],
expression,
updates=[(state, state+i)],
givens={
a : state
}
)
2
In [25]: f(1)
Out[25]: array(36)
1.2 Data
In [26]: x1 = np.linspace(-1, 1, 100)
x2 = 1.5 - x1 ** 2 + np.random.normal(scale=0.2, size=100)
x3 = np.random.normal(scale=0.3, size=100)
x4 = np.random.normal(scale=0.3, size=100)
permutation = np.random.permutation(np.arange(200))
x = np.hstack((
np.vstack((x1, x2)),
np.vstack((x3, x4)))).T[permutation]
y = np.concatenate((
np.zeros_like(x1),
np.ones_like(x3)))[permutation]
# needed for pictures later
xx, yy = np.mgrid[-2:2:.01, -2:2:.01]
grid_arr = np.c_[xx.ravel(), yy.ravel()]
def plot_decision(predicts):
probas = predicts.reshape(xx.shape)
contour = contourf(xx, yy, probas, 25, cmap="RdBu", vmin=0, vmax=1)
colorbar(contour)
scatter(x[:,0], x[:, 1], c=y, s=50,
cmap="RdBu", vmin=-.2, vmax=1.2,
edgecolor="white", linewidth=1)
title("Some cool decision boundary")
grid()
In [27]: scatter(x[:,0], x[:, 1], c=y, s=75,
cmap="RdBu", vmin=-.2, vmax=1.2,
edgecolor="white", linewidth=1)
title("Toy data")
grid()
3
1.3 Logistic regression
In [29]: # allocate variables
W = theano.shared(
value=numpy.zeros((2, 1),dtype=theano.config.floatX),
name=’W’,
borrow=True)
b = theano.shared(
value=numpy.zeros((1,), dtype=theano.config.floatX),
name=’b’,
borrow=True)
X = T.matrix(’X’)
Y = T.imatrix(’Y’)
index = T.lscalar()
shared_x = theano.shared(x.astype(theano.config.floatX))
shared_y = theano.shared(y.astype(np.int32)[..., np.newaxis])
In [30]: # define model
linear = T.dot(X, W) + b
p_y_given_x = T.nnet.sigmoid(linear)
y_pred = p_y_given_x > 0.5
4
cost = T.nnet.binary_crossentropy(p_y_given_x, Y).mean()
In [32]: # give me the gradients
g_W = T.grad(cost, W)
g_b = T.grad(cost, b)
learning_rate = 0.4
In [33]: batch_size = 4
updates = [(W,W - learning_rate * g_W),
(b, b - 2 * learning_rate * g_b)]
train = theano.function(
[index],
[cost],
updates=updates,
givens={
X: shared_x[index * batch_size: (index + 1) * batch_size],
Y: shared_y[index * batch_size: (index + 1) * batch_size]
}
)
In [34]: ## SGD is love SGD is life
for epoch_ in xrange(150):
loss = []
for iter_ in xrange(100 // batch_size):
loss.append(train(iter_))
e_loss = np.mean(loss)
if not epoch_ % 10:
print e_loss
0.493502346255
0.147674447402
0.128282895388
0.121076048693
0.11739237421
0.115212956857
0.113809215835
0.112853422221
0.112176679133
0.111683459472
0.111315944784
0.111037287761
0.110823034929
0.110656420058
0.110525636027
In [35]: # p_y_given_x = T.nnet.sigmoid(T.dot(X, W) + b)
predict_proba = theano.function(
5
[X],
p_y_given_x
)
probas = predict_proba(grid_arr)
In [36]: plot_decision(probas)
1.4 SVM
In [66]: # reset parameters
W.set_value(numpy.zeros((2, 1),dtype=theano.config.floatX),
borrow=True)
b.set_value(numpy.zeros((1,), dtype=theano.config.floatX),
borrow=True)
In [67]: # this is the only change needed to switch to SVM
y[y == 0] = -1
6
linear = T.dot(X ** 51 + X ** 5 + X ** 2, W) + b
cost = T.maximum(0, 1 - linear * Y).mean() + 2e-3 * (W ** 2).sum()
In [71]: #learning_rate = 0.01
# this code was not changed from above!
shared_x = theano.shared(x.astype(theano.config.floatX))
shared_y = theano.shared(y.astype(np.int32)[..., np.newaxis])
g_W = T.grad(cost, W)
g_b = T.grad(cost, b)
updates = [(W,W - learning_rate * g_W),
(b, b - 2 * learning_rate * g_b)]
train = theano.function(
[index],
[cost],
updates=updates,
givens={
X: shared_x[index * batch_size: (index + 1) * batch_size],
Y: shared_y[index * batch_size: (index + 1) * batch_size]
}
)
for epoch_ in xrange(150):
loss = []
for iter_ in xrange(100 // batch_size):
loss.append(train(iter_))
e_loss = np.mean(loss)
if not epoch_ % 10:
print e_loss
8.07245149444
5.08135669324
2.72128208817
1.32891962237
0.694687232703
0.388649249613
0.235258656813
0.148592129988
0.165618868736
0.165583407441
0.165459371865
0.160225021915
0.160102481692
0.160319361948
0.165628919804
In [64]: predict = theano.function(
[X],
linear > 0
)
In [72]: preds = predict(grid_arr)
plot_decision(preds)
7
8

Mais conteúdo relacionado

Mais procurados

Essence of the iterator pattern
Essence of the iterator patternEssence of the iterator pattern
Essence of the iterator patternMarkus Klink
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeLuka Jacobowitz
 
R programming lab 1 - jupyter notebook
R programming lab   1 - jupyter notebookR programming lab   1 - jupyter notebook
R programming lab 1 - jupyter notebookAshwini Mathur
 
Object Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesObject Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesDudy Ali
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersKimikazu Kato
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
15 - Scala. Dependent function type (Π-type)
15 - Scala. Dependent function type (Π-type)15 - Scala. Dependent function type (Π-type)
15 - Scala. Dependent function type (Π-type)Roman Brovko
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingSaurabh Singh
 
Type-level programming
Type-level programmingType-level programming
Type-level programmingDmytro Mitin
 

Mais procurados (19)

Matlab Nn Intro
Matlab Nn IntroMatlab Nn Intro
Matlab Nn Intro
 
Essence of the iterator pattern
Essence of the iterator patternEssence of the iterator pattern
Essence of the iterator pattern
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to Free
 
Exp 3-2 d 422
Exp 3-2  d 422Exp 3-2  d 422
Exp 3-2 d 422
 
Dynamic allocation
Dynamic allocationDynamic allocation
Dynamic allocation
 
R programming lab 1 - jupyter notebook
R programming lab   1 - jupyter notebookR programming lab   1 - jupyter notebook
R programming lab 1 - jupyter notebook
 
Object Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesObject Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference Types
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
 
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
Leniar datastructure
Leniar datastructureLeniar datastructure
Leniar datastructure
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
15 - Scala. Dependent function type (Π-type)
15 - Scala. Dependent function type (Π-type)15 - Scala. Dependent function type (Π-type)
15 - Scala. Dependent function type (Π-type)
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Demystifying Machine Learning
Demystifying Machine LearningDemystifying Machine Learning
Demystifying Machine Learning
 
knn classification
knn classificationknn classification
knn classification
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
NumPy Refresher
NumPy RefresherNumPy Refresher
NumPy Refresher
 
Type-level programming
Type-level programmingType-level programming
Type-level programming
 

Destaque

Understanding Large Social Networks | IRE Major Project | Team 57
Understanding Large Social Networks | IRE Major Project | Team 57 Understanding Large Social Networks | IRE Major Project | Team 57
Understanding Large Social Networks | IRE Major Project | Team 57 Raj Patel
 
Во внутренности Kivy
Во внутренности KivyВо внутренности Kivy
Во внутренности KivyPyNSK
 
Be Careful What You Wish For
Be Careful What You Wish ForBe Careful What You Wish For
Be Careful What You Wish ForMHS
 
Slovenia 2009
Slovenia 2009Slovenia 2009
Slovenia 2009kaytwin2
 
Что почитать вместе с дочерью.Pptx
Что почитать вместе с дочерью.PptxЧто почитать вместе с дочерью.Pptx
Что почитать вместе с дочерью.PptxIT Princess Academy
 
Классификация сигналов головного мозга для нейрокомпьютерного интерфейса
Классификация сигналов головного мозга для нейрокомпьютерного интерфейсаКлассификация сигналов головного мозга для нейрокомпьютерного интерфейса
Классификация сигналов головного мозга для нейрокомпьютерного интерфейсаAzoft
 
To infinity and Beyond with Plone 5!
To infinity and Beyond with Plone 5!To infinity and Beyond with Plone 5!
To infinity and Beyond with Plone 5!Rikupekka Oksanen
 
Динамика твёрдого тела: случай Лагранжа
Динамика твёрдого тела: случай ЛагранжаДинамика твёрдого тела: случай Лагранжа
Динамика твёрдого тела: случай ЛагранжаTheoretical mechanics department
 
гибридная книга
гибридная книгагибридная книга
гибридная книгаlibusue
 
Presentazione Open Day del Politecnico di Milano (2016)
Presentazione Open Day del Politecnico di Milano (2016)Presentazione Open Day del Politecnico di Milano (2016)
Presentazione Open Day del Politecnico di Milano (2016)Pier Luca Lanzi
 
Dbda勉強会~概要説明ochi20130803
Dbda勉強会~概要説明ochi20130803Dbda勉強会~概要説明ochi20130803
Dbda勉強会~概要説明ochi20130803Masanao Ochi
 
Introduzione alla realizzazione di videogiochi - Game Engine
Introduzione alla realizzazione di videogiochi - Game EngineIntroduzione alla realizzazione di videogiochi - Game Engine
Introduzione alla realizzazione di videogiochi - Game EnginePier Luca Lanzi
 
C++ для встраиваемых систем
C++ для встраиваемых системC++ для встраиваемых систем
C++ для встраиваемых системKirill Tikhonov
 

Destaque (18)

Quizzitch 2014 - Finals
Quizzitch 2014 - FinalsQuizzitch 2014 - Finals
Quizzitch 2014 - Finals
 
Understanding Large Social Networks | IRE Major Project | Team 57
Understanding Large Social Networks | IRE Major Project | Team 57 Understanding Large Social Networks | IRE Major Project | Team 57
Understanding Large Social Networks | IRE Major Project | Team 57
 
Во внутренности Kivy
Во внутренности KivyВо внутренности Kivy
Во внутренности Kivy
 
Cutre comic
Cutre comicCutre comic
Cutre comic
 
Be Careful What You Wish For
Be Careful What You Wish ForBe Careful What You Wish For
Be Careful What You Wish For
 
Slovenia 2009
Slovenia 2009Slovenia 2009
Slovenia 2009
 
Что почитать вместе с дочерью.Pptx
Что почитать вместе с дочерью.PptxЧто почитать вместе с дочерью.Pptx
Что почитать вместе с дочерью.Pptx
 
Сплайн интерполяция
Сплайн интерполяцияСплайн интерполяция
Сплайн интерполяция
 
Классификация сигналов головного мозга для нейрокомпьютерного интерфейса
Классификация сигналов головного мозга для нейрокомпьютерного интерфейсаКлассификация сигналов головного мозга для нейрокомпьютерного интерфейса
Классификация сигналов головного мозга для нейрокомпьютерного интерфейса
 
To infinity and Beyond with Plone 5!
To infinity and Beyond with Plone 5!To infinity and Beyond with Plone 5!
To infinity and Beyond with Plone 5!
 
Динамика твёрдого тела: случай Лагранжа
Динамика твёрдого тела: случай ЛагранжаДинамика твёрдого тела: случай Лагранжа
Динамика твёрдого тела: случай Лагранжа
 
The headless CMS
The headless CMSThe headless CMS
The headless CMS
 
гибридная книга
гибридная книгагибридная книга
гибридная книга
 
Presentazione Open Day del Politecnico di Milano (2016)
Presentazione Open Day del Politecnico di Milano (2016)Presentazione Open Day del Politecnico di Milano (2016)
Presentazione Open Day del Politecnico di Milano (2016)
 
Основы Python. Функции
Основы Python. ФункцииОсновы Python. Функции
Основы Python. Функции
 
Dbda勉強会~概要説明ochi20130803
Dbda勉強会~概要説明ochi20130803Dbda勉強会~概要説明ochi20130803
Dbda勉強会~概要説明ochi20130803
 
Introduzione alla realizzazione di videogiochi - Game Engine
Introduzione alla realizzazione di videogiochi - Game EngineIntroduzione alla realizzazione di videogiochi - Game Engine
Introduzione alla realizzazione di videogiochi - Game Engine
 
C++ для встраиваемых систем
C++ для встраиваемых системC++ для встраиваемых систем
C++ для встраиваемых систем
 

Semelhante a DF1 - Py - Ovcharenko - Theano Tutorial

Neural networks with python
Neural networks with pythonNeural networks with python
Neural networks with pythonSimone Piunno
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.pptebinazer1
 
Need help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docxNeed help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docxlauracallander
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and SparkOswald Campesato
 
Basic_analysis.ppt
Basic_analysis.pptBasic_analysis.ppt
Basic_analysis.pptSoumyaJ3
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docxjosies1
 
Naive application of Machine Learning to Software Development
Naive application of Machine Learning to Software DevelopmentNaive application of Machine Learning to Software Development
Naive application of Machine Learning to Software DevelopmentAndriy Khavryuchenko
 
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...FarhanAhmade
 
Pytorch for tf_developers
Pytorch for tf_developersPytorch for tf_developers
Pytorch for tf_developersAbdul Muneer
 
ML Assignment help.pptx
ML Assignment help.pptxML Assignment help.pptx
ML Assignment help.pptxRobinjk
 
Introduction to Tensorflow
Introduction to TensorflowIntroduction to Tensorflow
Introduction to TensorflowTzar Umang
 
Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)Ray Buse
 

Semelhante a DF1 - Py - Ovcharenko - Theano Tutorial (20)

Neural networks with python
Neural networks with pythonNeural networks with python
Neural networks with python
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
 
Need help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docxNeed help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docx
 
PyData Paris 2015 - Track 1.2 Gilles Louppe
PyData Paris 2015 - Track 1.2 Gilles LouppePyData Paris 2015 - Track 1.2 Gilles Louppe
PyData Paris 2015 - Track 1.2 Gilles Louppe
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and Spark
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
 
Basic_analysis.ppt
Basic_analysis.pptBasic_analysis.ppt
Basic_analysis.ppt
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
 
Naive application of Machine Learning to Software Development
Naive application of Machine Learning to Software DevelopmentNaive application of Machine Learning to Software Development
Naive application of Machine Learning to Software Development
 
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
 
Pytorch for tf_developers
Pytorch for tf_developersPytorch for tf_developers
Pytorch for tf_developers
 
NUMPY
NUMPY NUMPY
NUMPY
 
Mpi in-python
Mpi in-pythonMpi in-python
Mpi in-python
 
ML Assignment help.pptx
ML Assignment help.pptxML Assignment help.pptx
ML Assignment help.pptx
 
Introduction to Tensorflow
Introduction to TensorflowIntroduction to Tensorflow
Introduction to Tensorflow
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
 
Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)
 

Mais de MoscowDataFest

DF1 - R - Natekin - Improving Daily Analysis with data.table
DF1 - R - Natekin - Improving Daily Analysis with data.tableDF1 - R - Natekin - Improving Daily Analysis with data.table
DF1 - R - Natekin - Improving Daily Analysis with data.tableMoscowDataFest
 
DF1 - Py - Kalaidin - Introduction to Word Embeddings with Python
DF1 - Py - Kalaidin - Introduction to Word Embeddings with PythonDF1 - Py - Kalaidin - Introduction to Word Embeddings with Python
DF1 - Py - Kalaidin - Introduction to Word Embeddings with PythonMoscowDataFest
 
DF1 - ML - Petukhov - Azure Ml Machine Learning as a Service
DF1 - ML - Petukhov - Azure Ml Machine Learning as a ServiceDF1 - ML - Petukhov - Azure Ml Machine Learning as a Service
DF1 - ML - Petukhov - Azure Ml Machine Learning as a ServiceMoscowDataFest
 
DF1 - ML - Vorontsov - BigARTM Topic Modelling of Large Text Collections
DF1 - ML - Vorontsov - BigARTM Topic Modelling of Large Text CollectionsDF1 - ML - Vorontsov - BigARTM Topic Modelling of Large Text Collections
DF1 - ML - Vorontsov - BigARTM Topic Modelling of Large Text CollectionsMoscowDataFest
 
DF1 - DL - Lempitsky - Compact and Very Compact Image Descriptors
DF1 - DL - Lempitsky - Compact and Very Compact Image DescriptorsDF1 - DL - Lempitsky - Compact and Very Compact Image Descriptors
DF1 - DL - Lempitsky - Compact and Very Compact Image DescriptorsMoscowDataFest
 
DF1 - BD - Baranov - Mining Large Datasets with Apache Spark
DF1 - BD - Baranov - Mining Large Datasets with Apache SparkDF1 - BD - Baranov - Mining Large Datasets with Apache Spark
DF1 - BD - Baranov - Mining Large Datasets with Apache SparkMoscowDataFest
 
DF1 - BD - Degtiarev - Practical Aspects of Big Data in Pharmaceutical
DF1 - BD - Degtiarev - Practical Aspects of Big Data in PharmaceuticalDF1 - BD - Degtiarev - Practical Aspects of Big Data in Pharmaceutical
DF1 - BD - Degtiarev - Practical Aspects of Big Data in PharmaceuticalMoscowDataFest
 

Mais de MoscowDataFest (7)

DF1 - R - Natekin - Improving Daily Analysis with data.table
DF1 - R - Natekin - Improving Daily Analysis with data.tableDF1 - R - Natekin - Improving Daily Analysis with data.table
DF1 - R - Natekin - Improving Daily Analysis with data.table
 
DF1 - Py - Kalaidin - Introduction to Word Embeddings with Python
DF1 - Py - Kalaidin - Introduction to Word Embeddings with PythonDF1 - Py - Kalaidin - Introduction to Word Embeddings with Python
DF1 - Py - Kalaidin - Introduction to Word Embeddings with Python
 
DF1 - ML - Petukhov - Azure Ml Machine Learning as a Service
DF1 - ML - Petukhov - Azure Ml Machine Learning as a ServiceDF1 - ML - Petukhov - Azure Ml Machine Learning as a Service
DF1 - ML - Petukhov - Azure Ml Machine Learning as a Service
 
DF1 - ML - Vorontsov - BigARTM Topic Modelling of Large Text Collections
DF1 - ML - Vorontsov - BigARTM Topic Modelling of Large Text CollectionsDF1 - ML - Vorontsov - BigARTM Topic Modelling of Large Text Collections
DF1 - ML - Vorontsov - BigARTM Topic Modelling of Large Text Collections
 
DF1 - DL - Lempitsky - Compact and Very Compact Image Descriptors
DF1 - DL - Lempitsky - Compact and Very Compact Image DescriptorsDF1 - DL - Lempitsky - Compact and Very Compact Image Descriptors
DF1 - DL - Lempitsky - Compact and Very Compact Image Descriptors
 
DF1 - BD - Baranov - Mining Large Datasets with Apache Spark
DF1 - BD - Baranov - Mining Large Datasets with Apache SparkDF1 - BD - Baranov - Mining Large Datasets with Apache Spark
DF1 - BD - Baranov - Mining Large Datasets with Apache Spark
 
DF1 - BD - Degtiarev - Practical Aspects of Big Data in Pharmaceutical
DF1 - BD - Degtiarev - Practical Aspects of Big Data in PharmaceuticalDF1 - BD - Degtiarev - Practical Aspects of Big Data in Pharmaceutical
DF1 - BD - Degtiarev - Practical Aspects of Big Data in Pharmaceutical
 

Último

Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...anilsa9823
 
A relative description on Sonoporation.pdf
A relative description on Sonoporation.pdfA relative description on Sonoporation.pdf
A relative description on Sonoporation.pdfnehabiju2046
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfmuntazimhurra
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bSérgio Sacani
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Sérgio Sacani
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |aasikanpl
 
Analytical Profile of Coleus Forskohlii | Forskolin .pptx
Analytical Profile of Coleus Forskohlii | Forskolin .pptxAnalytical Profile of Coleus Forskohlii | Forskolin .pptx
Analytical Profile of Coleus Forskohlii | Forskolin .pptxSwapnil Therkar
 
Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxgindu3009
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRDelhi Call girls
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisDiwakar Mishra
 
G9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptG9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptMAESTRELLAMesa2
 
Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Patrick Diehl
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Nistarini College, Purulia (W.B) India
 
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡anilsa9823
 
Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTSérgio Sacani
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCEPRINCE C P
 
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptxUnlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptxanandsmhk
 

Último (20)

Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
 
A relative description on Sonoporation.pdf
A relative description on Sonoporation.pdfA relative description on Sonoporation.pdf
A relative description on Sonoporation.pdf
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdf
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
 
Engler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomyEngler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomy
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
The Philosophy of Science
The Philosophy of ScienceThe Philosophy of Science
The Philosophy of Science
 
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
 
Analytical Profile of Coleus Forskohlii | Forskolin .pptx
Analytical Profile of Coleus Forskohlii | Forskolin .pptxAnalytical Profile of Coleus Forskohlii | Forskolin .pptx
Analytical Profile of Coleus Forskohlii | Forskolin .pptx
 
Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptx
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
 
G9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptG9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.ppt
 
Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...
 
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
 
Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOST
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
 
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptxUnlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptx
 

DF1 - Py - Ovcharenko - Theano Tutorial

  • 1. DataFest Theano tutorial September 20, 2015 1 Introduction This is a basic theano tutorial, presented at the Moscow Data Fest: http://www.meetup.com/Moscow-Data- Fest/events/224856462/. You can find the code here: https://github.com/dudevil/datafest-theano-tutorial/. 1.1 Baby steps In [1]: import numpy as np import theano import theano.tensor as T %pylab inline figsize(8, 6) Populating the interactive namespace from numpy and matplotlib In [18]: # declare theano variable a = theano.tensor.lscalar() #a = theano.tensor.vector() expression = 1 + 2 * a + a ** 2 f = theano.function( [a], expression) In [7]: #f(0) result = f(np.arange(-10, 10)) result Out[7]: array([ 81., 64., 49., 36., 25., 16., 9., 4., 1., 0., 1., 4., 9., 16., 25., 36., 49., 64., 81., 100.]) In [8]: plot(np.arange(-10, 10), result, c=’m’, linewidth=2.) grid() 1
  • 2. In [9]: # shared variables represent internal state state = theano.shared(0) i = T.iscalar(’i’) accumulator = theano.function([i], state, updates=[(state, state+i)]) In [14]: accumulator(5) Out[14]: array(20) In [15]: state.set_value(-15) print state.get_value() -15 In [19]: state.set_value(0) f = theano.function( [i], expression, updates=[(state, state+i)], givens={ a : state } ) 2
  • 3. In [25]: f(1) Out[25]: array(36) 1.2 Data In [26]: x1 = np.linspace(-1, 1, 100) x2 = 1.5 - x1 ** 2 + np.random.normal(scale=0.2, size=100) x3 = np.random.normal(scale=0.3, size=100) x4 = np.random.normal(scale=0.3, size=100) permutation = np.random.permutation(np.arange(200)) x = np.hstack(( np.vstack((x1, x2)), np.vstack((x3, x4)))).T[permutation] y = np.concatenate(( np.zeros_like(x1), np.ones_like(x3)))[permutation] # needed for pictures later xx, yy = np.mgrid[-2:2:.01, -2:2:.01] grid_arr = np.c_[xx.ravel(), yy.ravel()] def plot_decision(predicts): probas = predicts.reshape(xx.shape) contour = contourf(xx, yy, probas, 25, cmap="RdBu", vmin=0, vmax=1) colorbar(contour) scatter(x[:,0], x[:, 1], c=y, s=50, cmap="RdBu", vmin=-.2, vmax=1.2, edgecolor="white", linewidth=1) title("Some cool decision boundary") grid() In [27]: scatter(x[:,0], x[:, 1], c=y, s=75, cmap="RdBu", vmin=-.2, vmax=1.2, edgecolor="white", linewidth=1) title("Toy data") grid() 3
  • 4. 1.3 Logistic regression In [29]: # allocate variables W = theano.shared( value=numpy.zeros((2, 1),dtype=theano.config.floatX), name=’W’, borrow=True) b = theano.shared( value=numpy.zeros((1,), dtype=theano.config.floatX), name=’b’, borrow=True) X = T.matrix(’X’) Y = T.imatrix(’Y’) index = T.lscalar() shared_x = theano.shared(x.astype(theano.config.floatX)) shared_y = theano.shared(y.astype(np.int32)[..., np.newaxis]) In [30]: # define model linear = T.dot(X, W) + b p_y_given_x = T.nnet.sigmoid(linear) y_pred = p_y_given_x > 0.5 4
  • 5. cost = T.nnet.binary_crossentropy(p_y_given_x, Y).mean() In [32]: # give me the gradients g_W = T.grad(cost, W) g_b = T.grad(cost, b) learning_rate = 0.4 In [33]: batch_size = 4 updates = [(W,W - learning_rate * g_W), (b, b - 2 * learning_rate * g_b)] train = theano.function( [index], [cost], updates=updates, givens={ X: shared_x[index * batch_size: (index + 1) * batch_size], Y: shared_y[index * batch_size: (index + 1) * batch_size] } ) In [34]: ## SGD is love SGD is life for epoch_ in xrange(150): loss = [] for iter_ in xrange(100 // batch_size): loss.append(train(iter_)) e_loss = np.mean(loss) if not epoch_ % 10: print e_loss 0.493502346255 0.147674447402 0.128282895388 0.121076048693 0.11739237421 0.115212956857 0.113809215835 0.112853422221 0.112176679133 0.111683459472 0.111315944784 0.111037287761 0.110823034929 0.110656420058 0.110525636027 In [35]: # p_y_given_x = T.nnet.sigmoid(T.dot(X, W) + b) predict_proba = theano.function( 5
  • 6. [X], p_y_given_x ) probas = predict_proba(grid_arr) In [36]: plot_decision(probas) 1.4 SVM In [66]: # reset parameters W.set_value(numpy.zeros((2, 1),dtype=theano.config.floatX), borrow=True) b.set_value(numpy.zeros((1,), dtype=theano.config.floatX), borrow=True) In [67]: # this is the only change needed to switch to SVM y[y == 0] = -1 6
  • 7. linear = T.dot(X ** 51 + X ** 5 + X ** 2, W) + b cost = T.maximum(0, 1 - linear * Y).mean() + 2e-3 * (W ** 2).sum() In [71]: #learning_rate = 0.01 # this code was not changed from above! shared_x = theano.shared(x.astype(theano.config.floatX)) shared_y = theano.shared(y.astype(np.int32)[..., np.newaxis]) g_W = T.grad(cost, W) g_b = T.grad(cost, b) updates = [(W,W - learning_rate * g_W), (b, b - 2 * learning_rate * g_b)] train = theano.function( [index], [cost], updates=updates, givens={ X: shared_x[index * batch_size: (index + 1) * batch_size], Y: shared_y[index * batch_size: (index + 1) * batch_size] } ) for epoch_ in xrange(150): loss = [] for iter_ in xrange(100 // batch_size): loss.append(train(iter_)) e_loss = np.mean(loss) if not epoch_ % 10: print e_loss 8.07245149444 5.08135669324 2.72128208817 1.32891962237 0.694687232703 0.388649249613 0.235258656813 0.148592129988 0.165618868736 0.165583407441 0.165459371865 0.160225021915 0.160102481692 0.160319361948 0.165628919804 In [64]: predict = theano.function( [X], linear > 0 ) In [72]: preds = predict(grid_arr) plot_decision(preds) 7
  • 8. 8