SlideShare a Scribd company logo
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

More Related Content

What's hot

Matlab Nn Intro
Matlab Nn IntroMatlab Nn Intro
Matlab Nn Intro
Imthias Ahamed
 
Essence of the iterator pattern
Essence of the iterator patternEssence of the iterator pattern
Essence of the iterator pattern
Markus 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 Free
Luka Jacobowitz
 
Exp 3-2 d 422
Exp 3-2  d 422Exp 3-2  d 422
Exp 3-2 d 422
Omkar Rane
 
Dynamic allocation
Dynamic allocationDynamic allocation
Dynamic allocation
CGC Technical campus,Mohali
 
R programming lab 1 - jupyter notebook
R programming lab   1 - jupyter notebookR programming lab   1 - jupyter notebook
R programming lab 1 - jupyter notebook
Ashwini 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 Types
Dudy 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 Programmers
Kimikazu Kato
 
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...
The Statistical and Applied Mathematical Sciences Institute
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
Enthought, Inc.
 
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
Kimikazu 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 Programming
Saurabh Singh
 
Demystifying Machine Learning
Demystifying Machine LearningDemystifying Machine Learning
Demystifying Machine Learning
Vaideeswaran Sethuraman
 
knn classification
knn classificationknn classification
knn classification
Akhilesh Joshi
 
C++ Template
C++ TemplateC++ Template
C++ Template
Saket Pathak
 
NumPy Refresher
NumPy RefresherNumPy Refresher
NumPy Refresher
Lukasz Dobrzanski
 
Type-level programming
Type-level programmingType-level programming
Type-level programming
Dmytro Mitin
 

What's hot (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
 

Viewers also liked

Quizzitch 2014 - Finals
Quizzitch 2014 - FinalsQuizzitch 2014 - Finals
Quizzitch 2014 - Finals
Nishant Prateek
 
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
Во внутренности Kivy
PyNSK
 
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
Что почитать вместе с дочерью.Pptx
IT 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
 
The headless CMS
The headless CMSThe headless CMS
The headless CMS
Érico Andrei
 
гибридная книга
гибридная книгагибридная книга
гибридная книга
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
 
Основы Python. Функции
Основы Python. ФункцииОсновы Python. Функции
Основы Python. Функции
Theoretical mechanics department
 
Dbda勉強会~概要説明ochi20130803
Dbda勉強会~概要説明ochi20130803Dbda勉強会~概要説明ochi20130803
Dbda勉強会~概要説明ochi20130803
Masanao 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 Engine
Pier Luca Lanzi
 
C++ для встраиваемых систем
C++ для встраиваемых системC++ для встраиваемых систем
C++ для встраиваемых систем
Kirill Tikhonov
 

Viewers also liked (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++ для встраиваемых систем
 

Similar to DF1 - Py - Ovcharenko - Theano Tutorial

Neural networks with python
Neural networks with pythonNeural networks with python
Neural networks with python
Simone Piunno
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
ebinazer1
 
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
lauracallander
 
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
Pôle Systematic Paris-Region
 
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
Arnaud Joly
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and Spark
Oswald Campesato
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
SankarTerli
 
Basic_analysis.ppt
Basic_analysis.pptBasic_analysis.ppt
Basic_analysis.ppt
SoumyaJ3
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
Abdul 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.docx
josies1
 
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
Andriy 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_developers
Abdul Muneer
 
NUMPY
NUMPY NUMPY
Mpi in-python
Mpi in-pythonMpi in-python
Mpi in-python
A Jorge Garcia
 
ML Assignment help.pptx
ML Assignment help.pptxML Assignment help.pptx
ML Assignment help.pptx
Robinjk
 
Introduction to Tensorflow
Introduction to TensorflowIntroduction to Tensorflow
Introduction to Tensorflow
Tzar Umang
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
Alpha337901
 
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
 

Similar to 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)
 

More from 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.table
MoscowDataFest
 
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
MoscowDataFest
 
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
MoscowDataFest
 
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
MoscowDataFest
 
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
MoscowDataFest
 
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
MoscowDataFest
 
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
MoscowDataFest
 

More from 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
 

Recently uploaded

SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdfSCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SELF-EXPLANATORY
 
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
Scintica Instrumentation
 
Hemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptxHemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptx
muralinath2
 
Cancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate PathwayCancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate Pathway
AADYARAJPANDEY1
 
extra-chromosomal-inheritance[1].pptx.pdfpdf
extra-chromosomal-inheritance[1].pptx.pdfpdfextra-chromosomal-inheritance[1].pptx.pdfpdf
extra-chromosomal-inheritance[1].pptx.pdfpdf
DiyaBiswas10
 
Unveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdfUnveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdf
Erdal Coalmaker
 
Anemia_ different types_causes_ conditions
Anemia_ different types_causes_ conditionsAnemia_ different types_causes_ conditions
Anemia_ different types_causes_ conditions
muralinath2
 
RNA INTERFERENCE: UNRAVELING GENETIC SILENCING
RNA INTERFERENCE: UNRAVELING GENETIC SILENCINGRNA INTERFERENCE: UNRAVELING GENETIC SILENCING
RNA INTERFERENCE: UNRAVELING GENETIC SILENCING
AADYARAJPANDEY1
 
ESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptxESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptx
muralinath2
 
Structures and textures of metamorphic rocks
Structures and textures of metamorphic rocksStructures and textures of metamorphic rocks
Structures and textures of metamorphic rocks
kumarmathi863
 
Nutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technologyNutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technology
Lokesh Patil
 
The ASGCT Annual Meeting was packed with exciting progress in the field advan...
The ASGCT Annual Meeting was packed with exciting progress in the field advan...The ASGCT Annual Meeting was packed with exciting progress in the field advan...
The ASGCT Annual Meeting was packed with exciting progress in the field advan...
Health Advances
 
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Sérgio Sacani
 
plant biotechnology Lecture note ppt.pptx
plant biotechnology Lecture note ppt.pptxplant biotechnology Lecture note ppt.pptx
plant biotechnology Lecture note ppt.pptx
yusufzako14
 
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Sérgio Sacani
 
platelets_clotting_biogenesis.clot retractionpptx
platelets_clotting_biogenesis.clot retractionpptxplatelets_clotting_biogenesis.clot retractionpptx
platelets_clotting_biogenesis.clot retractionpptx
muralinath2
 
Seminar of U.V. Spectroscopy by SAMIR PANDA
 Seminar of U.V. Spectroscopy by SAMIR PANDA Seminar of U.V. Spectroscopy by SAMIR PANDA
Seminar of U.V. Spectroscopy by SAMIR PANDA
SAMIR PANDA
 
Penicillin...........................pptx
Penicillin...........................pptxPenicillin...........................pptx
Penicillin...........................pptx
Cherry
 
Predicting property prices with machine learning algorithms.pdf
Predicting property prices with machine learning algorithms.pdfPredicting property prices with machine learning algorithms.pdf
Predicting property prices with machine learning algorithms.pdf
binhminhvu04
 
Lateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensiveLateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensive
silvermistyshot
 

Recently uploaded (20)

SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdfSCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
 
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
 
Hemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptxHemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptx
 
Cancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate PathwayCancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate Pathway
 
extra-chromosomal-inheritance[1].pptx.pdfpdf
extra-chromosomal-inheritance[1].pptx.pdfpdfextra-chromosomal-inheritance[1].pptx.pdfpdf
extra-chromosomal-inheritance[1].pptx.pdfpdf
 
Unveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdfUnveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdf
 
Anemia_ different types_causes_ conditions
Anemia_ different types_causes_ conditionsAnemia_ different types_causes_ conditions
Anemia_ different types_causes_ conditions
 
RNA INTERFERENCE: UNRAVELING GENETIC SILENCING
RNA INTERFERENCE: UNRAVELING GENETIC SILENCINGRNA INTERFERENCE: UNRAVELING GENETIC SILENCING
RNA INTERFERENCE: UNRAVELING GENETIC SILENCING
 
ESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptxESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptx
 
Structures and textures of metamorphic rocks
Structures and textures of metamorphic rocksStructures and textures of metamorphic rocks
Structures and textures of metamorphic rocks
 
Nutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technologyNutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technology
 
The ASGCT Annual Meeting was packed with exciting progress in the field advan...
The ASGCT Annual Meeting was packed with exciting progress in the field advan...The ASGCT Annual Meeting was packed with exciting progress in the field advan...
The ASGCT Annual Meeting was packed with exciting progress in the field advan...
 
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
 
plant biotechnology Lecture note ppt.pptx
plant biotechnology Lecture note ppt.pptxplant biotechnology Lecture note ppt.pptx
plant biotechnology Lecture note ppt.pptx
 
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
 
platelets_clotting_biogenesis.clot retractionpptx
platelets_clotting_biogenesis.clot retractionpptxplatelets_clotting_biogenesis.clot retractionpptx
platelets_clotting_biogenesis.clot retractionpptx
 
Seminar of U.V. Spectroscopy by SAMIR PANDA
 Seminar of U.V. Spectroscopy by SAMIR PANDA Seminar of U.V. Spectroscopy by SAMIR PANDA
Seminar of U.V. Spectroscopy by SAMIR PANDA
 
Penicillin...........................pptx
Penicillin...........................pptxPenicillin...........................pptx
Penicillin...........................pptx
 
Predicting property prices with machine learning algorithms.pdf
Predicting property prices with machine learning algorithms.pdfPredicting property prices with machine learning algorithms.pdf
Predicting property prices with machine learning algorithms.pdf
 
Lateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensiveLateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensive
 

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