SlideShare a Scribd company logo
Machine Learning 101
Teach your computer the difference 

between cats and dogs
Cole Howard & Hannes Hapke
Open Source Bridge, June 23rd, 2016
Who are we?
John Howard

@uglyboxer

Senior Developer at Dark Horse Comics
Master of recommendation systems,
convolutional neural networks
Hannes Hapke

@hanneshapke

Senior Developer at CrowdStreet
Excited about neural networks 

applications
We want to show you how you can
train a computer to “recognize”
images *
* aka to decide between cats and dogs
What is this all about ...
Convolutional Nets are good
at determining ...
• The spatial relationship of data
• And therefore detecting determining patterns
Are these
dogs?
Convolutional Neural Nets
are heavily used by
For detecting patterns in images, videos, sounds and texts
• Music recommendation at Spotify 

(http://benanne.github.io/2014/08/05/spotify-cnns.html)
• Google’s PlaNet—Photo Geolocation with CNN 

(http://arxiv.org/abs/1602.05314)
• Who else is using CNNs? 

(https://www.quora.com/Apart-from-Google-Facebook-who-is-commercially-using-deep-recurrent-convolutional-
neural-networks)

What are conv nets?
• In traditional feed-forward networks, 

we are learning weights to apply to the data
• In conv-nets, we are learning to describe filters
• After each convolutional layer we still have an
“image”
• Instead of 3 channels (r-g-b), 

we have n - channels. 

Each described by one of the learned filters
Convolutional Neural Net
Filters (or Kernels)
Example of Edge
Detector
Example of Blurring
Filter
Pooling
• Can condense information as filters pull details apart
• With MaxPooling we take the local maximum activation
as representative of the region. 

Usually a 2x2 subsample
• As we filter, precise location becomes less relevant
• This condenses the amount of information 

by ¼ per learned channel
• BONUS: Net becomes tolerant to local perturbations in
the data
Traditional Feed-Forward
Icing on the Cake
• Flatten the filtered image 

into one long 1 dimensional vector
• Pass into a feed forward network
• Out to classes -> to determine error
• Learn like normal - backpropagation works on
filter weights, just as it does on neuron
weights
Convolutional Neural Net
What frameworks are
available?
Theano
• Created by the 

University of Montreal
• Framework for 

symbolic computation
• Provides GPU support



• Great Python libraries based on Theano: 

Keras, Lasagne, PyLearn2
import numpy
import theano.tensor as T
x = T.dmatrix('x')
y = T.dmatrix('y')
z = x + y
f = function([x, y], z)
TensorFlow
• Developed by a small startup in Moutainview
• Used for 50 Google products
• Used as part of AlphaGo (trained on TPUs*)
• Designed for distributed learning problems
• Growing ecosystem: TensorBoard, tflearn,
scikit-flow
import tensorflow as tf
a = tf.placeholder("float")
b = tf.placeholder("float")
y = tf.mul(a, b) # multiply the symbolic variables
with tf.Session() as sess:
print("%f should equal 2.0" % sess.run(y, feed_dict={a: 1, b: 2}))
print("%f should equal 9.0" % sess.run(y, feed_dict={a: 3, b: 3}))
How to prepare your
images for the
classification?
Normalize the image size
• Use the pillow package in Python
• For small size differences, squeeze images
• For larger differences, resize images
• Or use Keras’ pre-processing functions
y, x = image.size
y = x if x > y else y
resized_image = Image.new(color_schema, (y, y), (255, ))
try:
resized_image.paste(image, image.getbbox())
except ValueError:
continue
resized_image = resized_image.resize(

(resized_px, resized_px), Image.ANTIALIAS)
resized_image.save(new_filename, 'jpeg', quality=90)
Convert the images into
matrices
• Use the numpy package in Python
• No magic, use numpy’s asarray method
• Create a classification vector at the same time
image = Image.open(directory + f)
image.load()
image_matrix = np.asarray(image, dtype="int32").T
image_classification = 1 if animal == 'Cat/' else 0
data.append(image_matrix)
classification.append(image_classification)
Save the matrices in a
reusable format
• Pickle or numpy is your best friend
• You can split the dataset into training/test set
with `train_test_split`



• Store matrices as compressed pickles (use
numpy for large arrays)
• Use compression!
X_train, X_test, y_train, y_test = train_test_split(
data, classification, test_size=0.20, random_state=42)
np.savez_compressed('petsTrainingData.npz',
X_train=X_train, X_test=X_test,
y_train=y_train, y_test=y_test)
How to assemble 

a simple CNN 

with Keras
What is Keras? Why?
• Excellent Python wrapper library for Theano
• Supports TensorFlow too!
• Growing TensorFlow support
• Amazing documentation
• Amazing community
Steps
1. Setup your sequential model
2. Create a network structure
3. Set the “compile” parameters
4. Set the fit parameters
Setup a sequential model
• Sequential models allow you to define the
network structure

• Use model.add() to add layers to the neural
network
Model = Sequential()
model.add(Convolution2D(64, 2, 2, border_mode='same'))
Create your network
structure
• Keras provides various types of layers
• Convolution2D
• Convolution3D
• Dense
• Dropout
• Activation
• MaxPooling2D
• etc.
model.add(Convolution2D(64, 2, 2))
model.add(Activation(‘relu’))
model.add(MaxPooling2D(pool_size=(2, 2)))
Set the “compile”
parameters
• Keras provides various options for optimizing
your network
• SGD
• Adagrad
• Adadelta
• Etc.
• Set the learning rate, momentum, etc.
• Define your loss definition and metrics
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(
loss=‘categorical_crossentropy',
optimizer=sgd, metrics=['accuracy'])
Set the fit parameters
• This is where the magic starts!
• model.fit() allows you to define:
• The batch size
• Number of epochs
• Whether you want to shuffle your training data
• Your validation set
• Your callbacks

• Callbacks are amazing!
Use Callbacks
• Keras comes with various callbacks
• ModelCheckpoint 

allows saving the model parameters after every/best run
• EarlyStopping 

allows stopping the training if your training condition is met

• Other callbacks:
• LearningRateScheduler
• TensorBoard
• RemoteMonitor
Faster, Faster …
• GPU’s are your friends
• Unlike traditional feed-forward nets, there are large parts of CNN’s
that are parallel-izable!
• As each neuron normally depends on the neuron before it and the
error reported from the neuron after it, filters are different.
• In a layer, each filter and each filter at each position are
independent of each other.
• So all of those computations can happen simultaneously.
• And as all are simple matrix multiplications, we can make use of
the 1000’s of cores on modern GPU’s
Running on a GPU
• Install proper dependencies (linux requires a few extra steps here)
• Install Theano, Keras
• Install CUDA (http://tleyden.github.io/blog/2015/11/22/cuda-7-
dot-5-on-aws-gpu-instance-running-ubuntu-14-dot-04/)
• Install cuDNN (requires registration with NVIDIA)
• Configurations in ~/.theanorc
• Set Theano Flags when running script (or in .theanorc)
• Pre-configured AMI on AWS 

(ami-a6ec17c6 in region US-west-2/Oregon)
How does a training
look like in action?
Introduction to Convolutional Neural Networks
What to do once the
training is completed?
Introduction to Convolutional Neural Networks
Learning resources
ConvNets
• http://cs231n.stanford.edu/
• https://www.youtube.com/watch?v=bEUX_56Lojc
• http://blog.keras.io/how-convolutional-neural-networks-
see-the-world.html
Keras
• https://www.youtube.com/watch?v=Tp3SaRbql4k
TensorFlow
• http://learningtensorflow.com/examples/
Thank you!
bit.ly/OSB16-machinelearning101

More Related Content

PDF
Deep learning
Mohamed Loey
 
PDF
Deep learning - A Visual Introduction
Lukas Masuch
 
PPTX
Object recognition of CIFAR - 10
Ratul Alahy
 
PDF
Convolutional neural network
Yan Xu
 
PPTX
Image classification using CNN
Noura Hussein
 
PDF
An introduction to Deep Learning
Julien SIMON
 
PDF
CIFAR-10
satyam_madala
 
PPTX
Supervised and Unsupervised Learning In Machine Learning | Machine Learning T...
Simplilearn
 
Deep learning
Mohamed Loey
 
Deep learning - A Visual Introduction
Lukas Masuch
 
Object recognition of CIFAR - 10
Ratul Alahy
 
Convolutional neural network
Yan Xu
 
Image classification using CNN
Noura Hussein
 
An introduction to Deep Learning
Julien SIMON
 
CIFAR-10
satyam_madala
 
Supervised and Unsupervised Learning In Machine Learning | Machine Learning T...
Simplilearn
 

What's hot (20)

PPTX
Introduction to Deep Learning
Oswald Campesato
 
PDF
An Introduction to Deep Learning
Poo Kuan Hoong
 
PPTX
Introduction to Deep learning
leopauly
 
PPTX
Deep learning
Hatim EL-QADDOURY
 
PPTX
Cat and dog classification
omaraldabash
 
PDF
Deep Learning - Convolutional Neural Networks
Christian Perone
 
PDF
Deep learning for real life applications
Anas Arram, Ph.D
 
PPTX
Deep Learning Tutorial
Amr Rashed
 
PPTX
Convolutional neural network
MojammilHusain
 
PPTX
Transfer Learning and Fine-tuning Deep Neural Networks
PyData
 
PDF
Neural networks and deep learning
Jörgen Sandig
 
PPS
Neural Networks
Ismail El Gayar
 
PPTX
Face recognition using neural network
Indira Nayak
 
PPTX
Object detection
ROUSHAN RAJ KUMAR
 
PPT
Machine Learning
Rahul Kumar
 
PPTX
Image classification using convolutional neural network
KIRAN R
 
PPTX
Deep learning presentation
Tunde Ajose-Ismail
 
PPTX
Machine learning seminar ppt
RAHUL DANGWAL
 
PPTX
Convolutional Neural Networks
milad abbasi
 
DOCX
Digit recognition using mnist database
btandale
 
Introduction to Deep Learning
Oswald Campesato
 
An Introduction to Deep Learning
Poo Kuan Hoong
 
Introduction to Deep learning
leopauly
 
Deep learning
Hatim EL-QADDOURY
 
Cat and dog classification
omaraldabash
 
Deep Learning - Convolutional Neural Networks
Christian Perone
 
Deep learning for real life applications
Anas Arram, Ph.D
 
Deep Learning Tutorial
Amr Rashed
 
Convolutional neural network
MojammilHusain
 
Transfer Learning and Fine-tuning Deep Neural Networks
PyData
 
Neural networks and deep learning
Jörgen Sandig
 
Neural Networks
Ismail El Gayar
 
Face recognition using neural network
Indira Nayak
 
Object detection
ROUSHAN RAJ KUMAR
 
Machine Learning
Rahul Kumar
 
Image classification using convolutional neural network
KIRAN R
 
Deep learning presentation
Tunde Ajose-Ismail
 
Machine learning seminar ppt
RAHUL DANGWAL
 
Convolutional Neural Networks
milad abbasi
 
Digit recognition using mnist database
btandale
 
Ad

Viewers also liked (20)

PDF
Convolutional Neural Networks (CNN)
Gaurav Mittal
 
PPTX
Convolution as matrix multiplication
Edwin Efraín Jiménez Lepe
 
PDF
101: Convolutional Neural Networks
Mad Scientists
 
PDF
Convolutional neural network in practice
남주 김
 
PDF
Convolution Neural Networks
AhmedMahany
 
PPTX
Lecture 29 Convolutional Neural Networks - Computer Vision Spring2015
Jia-Bin Huang
 
PPTX
Deep Learning - Convolutional Neural Networks - Architectural Zoo
Christian Perone
 
PDF
Deep Learning - The Past, Present and Future of Artificial Intelligence
Lukas Masuch
 
PPTX
Deep neural networks
Si Haem
 
PDF
AI&BigData Lab. Артем Чернодуб "Распознавание изображений методом Lazy Deep ...
GeeksLab Odessa
 
PPTX
Neuroevolution and deep learing
Accenture
 
PPTX
CNN Tutorial
Sungjoon Choi
 
PDF
Convolution codes - Coding/Decoding Tree codes and Trellis codes for multiple...
Madhumita Tamhane
 
PPTX
Introduction to CNN
Shuai Zhang
 
PDF
Case Study of Convolutional Neural Network
NamHyuk Ahn
 
PDF
Deep Learning, an interactive introduction for NLP-ers
Roelof Pieters
 
PPTX
Introduction Of Artificial neural network
Nagarajan
 
PPTX
Neural network & its applications
Ahmed_hashmi
 
PDF
Artificial neural networks
stellajoseph
 
PDF
Deep learning - Conceptual understanding and applications
Buhwan Jeong
 
Convolutional Neural Networks (CNN)
Gaurav Mittal
 
Convolution as matrix multiplication
Edwin Efraín Jiménez Lepe
 
101: Convolutional Neural Networks
Mad Scientists
 
Convolutional neural network in practice
남주 김
 
Convolution Neural Networks
AhmedMahany
 
Lecture 29 Convolutional Neural Networks - Computer Vision Spring2015
Jia-Bin Huang
 
Deep Learning - Convolutional Neural Networks - Architectural Zoo
Christian Perone
 
Deep Learning - The Past, Present and Future of Artificial Intelligence
Lukas Masuch
 
Deep neural networks
Si Haem
 
AI&BigData Lab. Артем Чернодуб "Распознавание изображений методом Lazy Deep ...
GeeksLab Odessa
 
Neuroevolution and deep learing
Accenture
 
CNN Tutorial
Sungjoon Choi
 
Convolution codes - Coding/Decoding Tree codes and Trellis codes for multiple...
Madhumita Tamhane
 
Introduction to CNN
Shuai Zhang
 
Case Study of Convolutional Neural Network
NamHyuk Ahn
 
Deep Learning, an interactive introduction for NLP-ers
Roelof Pieters
 
Introduction Of Artificial neural network
Nagarajan
 
Neural network & its applications
Ahmed_hashmi
 
Artificial neural networks
stellajoseph
 
Deep learning - Conceptual understanding and applications
Buhwan Jeong
 
Ad

Similar to Introduction to Convolutional Neural Networks (20)

PPTX
Keras on tensorflow in R & Python
Longhow Lam
 
PDF
dfdshofdifhdifhdfhgfoighfgofgfgfgfgdfdfdfdf
nguyenhoangy207
 
PDF
NLP and Deep Learning for non_experts
Sanghamitra Deb
 
PPTX
Automatic Attendace using convolutional neural network Face Recognition
vatsal199567
 
PDF
Python for Image Understanding: Deep Learning with Convolutional Neural Nets
Roelof Pieters
 
PDF
Eye deep
sveitser
 
PPTX
Deep Neural Networks for Computer Vision
Alex Conway
 
PPTX
Demystifying-AI-Frameworks-TensorFlow-PyTorch-JAX-and-More (1).pptx
Anant Garg
 
PPTX
BRV CTO Summit Deep Learning Talk
Doug Chang
 
PPTX
cnn ppt.pptx
rohithprabhas1
 
PDF
Neural Networks from Scratch - TensorFlow 101
Gerold Bausch
 
PPTX
Convolutional Neural Networks for Computer vision Applications
Alex Conway
 
PPTX
Deep Learning for Computer Vision - PyconDE 2017
Alex Conway
 
PPTX
Artificial Intelligence, Machine Learning and Deep Learning
Sujit Pal
 
PDF
PyDresden 20170824 - Deep Learning for Computer Vision
Alex Conway
 
PPTX
Neural networks and deep learning
RADO7900
 
PPTX
Machine learning project
Harsh Jain
 
PPTX
Deep learning with TensorFlow
Barbara Fusinska
 
PDF
Learning keras by building dogs-vs-cats image classifier
Jian Wu
 
Keras on tensorflow in R & Python
Longhow Lam
 
dfdshofdifhdifhdfhgfoighfgofgfgfgfgdfdfdfdf
nguyenhoangy207
 
NLP and Deep Learning for non_experts
Sanghamitra Deb
 
Automatic Attendace using convolutional neural network Face Recognition
vatsal199567
 
Python for Image Understanding: Deep Learning with Convolutional Neural Nets
Roelof Pieters
 
Eye deep
sveitser
 
Deep Neural Networks for Computer Vision
Alex Conway
 
Demystifying-AI-Frameworks-TensorFlow-PyTorch-JAX-and-More (1).pptx
Anant Garg
 
BRV CTO Summit Deep Learning Talk
Doug Chang
 
cnn ppt.pptx
rohithprabhas1
 
Neural Networks from Scratch - TensorFlow 101
Gerold Bausch
 
Convolutional Neural Networks for Computer vision Applications
Alex Conway
 
Deep Learning for Computer Vision - PyconDE 2017
Alex Conway
 
Artificial Intelligence, Machine Learning and Deep Learning
Sujit Pal
 
PyDresden 20170824 - Deep Learning for Computer Vision
Alex Conway
 
Neural networks and deep learning
RADO7900
 
Machine learning project
Harsh Jain
 
Deep learning with TensorFlow
Barbara Fusinska
 
Learning keras by building dogs-vs-cats image classifier
Jian Wu
 

More from Hannes Hapke (6)

PDF
PDXPortland - Dockerize Django
Hannes Hapke
 
PDF
Introduction to Neural Networks - Perceptron
Hannes Hapke
 
PDF
PyDX Presentation about Python, GeoData and Maps
Hannes Hapke
 
PDF
Share your code with the Python world by
 creating pip packages
Hannes Hapke
 
PDF
Create responsive websites with Django, REST and AngularJS
Hannes Hapke
 
PDF
Python Ecosystem for Beginners - PyCon Uruguay 2013
Hannes Hapke
 
PDXPortland - Dockerize Django
Hannes Hapke
 
Introduction to Neural Networks - Perceptron
Hannes Hapke
 
PyDX Presentation about Python, GeoData and Maps
Hannes Hapke
 
Share your code with the Python world by
 creating pip packages
Hannes Hapke
 
Create responsive websites with Django, REST and AngularJS
Hannes Hapke
 
Python Ecosystem for Beginners - PyCon Uruguay 2013
Hannes Hapke
 

Recently uploaded (20)

PDF
Mastering Query Optimization Techniques for Modern Data Engineers
Accentfuture
 
PPTX
Data-Driven Machine Learning for Rail Infrastructure Health Monitoring
Sione Palu
 
PDF
Mastering Financial Analysis Materials.pdf
SalamiAbdullahi
 
PDF
Data Science Trends & Career Guide---ppt
jisajoy3061
 
PPTX
Global journeys: estimating international migration
Office for National Statistics
 
PPTX
Complete_STATA_Introduction_Beginner.pptx
mbayekebe
 
PPTX
Machine Learning Solution for Power Grid Cybersecurity with GraphWavelets
Sione Palu
 
PPTX
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
abhinavmemories2026
 
PDF
345_IT infrastructure for business management.pdf
LEANHTRAN4
 
PDF
Master Databricks SQL with AccentFuture – The Future of Data Warehousing
Accentfuture
 
PPTX
Economic Sector Performance Recovery.pptx
yulisbaso2020
 
PPTX
Trading Procedures (1).pptxcffcdddxxddsss
garv794
 
PDF
TCP_IP for Programmers ------ slides.pdf
Souhailsouhail5
 
PPTX
Understanding Prototyping in Design and Development
SadiaJanjua2
 
PDF
TIC ACTIVIDAD 1geeeeeeeeeeeeeeeeeeeeeeeeeeeeeer3.pdf
Thais Ruiz
 
PPTX
Major-Components-ofNKJNNKNKNKNKronment.pptx
dushyantsharma1221
 
PPT
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
JanakiRaman206018
 
PPTX
GR3-PPTFINAL (1).pptx 0.91 MbHIHUHUGG,HJGH
DarylArellaga1
 
PPTX
Extract Transformation Load (3) (1).pptx
revathi148366
 
PPTX
International-health-agency and it's work.pptx
shreehareeshgs
 
Mastering Query Optimization Techniques for Modern Data Engineers
Accentfuture
 
Data-Driven Machine Learning for Rail Infrastructure Health Monitoring
Sione Palu
 
Mastering Financial Analysis Materials.pdf
SalamiAbdullahi
 
Data Science Trends & Career Guide---ppt
jisajoy3061
 
Global journeys: estimating international migration
Office for National Statistics
 
Complete_STATA_Introduction_Beginner.pptx
mbayekebe
 
Machine Learning Solution for Power Grid Cybersecurity with GraphWavelets
Sione Palu
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
abhinavmemories2026
 
345_IT infrastructure for business management.pdf
LEANHTRAN4
 
Master Databricks SQL with AccentFuture – The Future of Data Warehousing
Accentfuture
 
Economic Sector Performance Recovery.pptx
yulisbaso2020
 
Trading Procedures (1).pptxcffcdddxxddsss
garv794
 
TCP_IP for Programmers ------ slides.pdf
Souhailsouhail5
 
Understanding Prototyping in Design and Development
SadiaJanjua2
 
TIC ACTIVIDAD 1geeeeeeeeeeeeeeeeeeeeeeeeeeeeeer3.pdf
Thais Ruiz
 
Major-Components-ofNKJNNKNKNKNKronment.pptx
dushyantsharma1221
 
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
JanakiRaman206018
 
GR3-PPTFINAL (1).pptx 0.91 MbHIHUHUGG,HJGH
DarylArellaga1
 
Extract Transformation Load (3) (1).pptx
revathi148366
 
International-health-agency and it's work.pptx
shreehareeshgs
 

Introduction to Convolutional Neural Networks

  • 1. Machine Learning 101 Teach your computer the difference 
 between cats and dogs Cole Howard & Hannes Hapke Open Source Bridge, June 23rd, 2016
  • 2. Who are we? John Howard
 @uglyboxer
 Senior Developer at Dark Horse Comics Master of recommendation systems, convolutional neural networks Hannes Hapke
 @hanneshapke
 Senior Developer at CrowdStreet Excited about neural networks 
 applications
  • 3. We want to show you how you can train a computer to “recognize” images * * aka to decide between cats and dogs What is this all about ...
  • 4. Convolutional Nets are good at determining ... • The spatial relationship of data • And therefore detecting determining patterns Are these dogs?
  • 5. Convolutional Neural Nets are heavily used by For detecting patterns in images, videos, sounds and texts • Music recommendation at Spotify 
 (http://benanne.github.io/2014/08/05/spotify-cnns.html) • Google’s PlaNet—Photo Geolocation with CNN 
 (http://arxiv.org/abs/1602.05314) • Who else is using CNNs? 
 (https://www.quora.com/Apart-from-Google-Facebook-who-is-commercially-using-deep-recurrent-convolutional- neural-networks)

  • 6. What are conv nets? • In traditional feed-forward networks, 
 we are learning weights to apply to the data • In conv-nets, we are learning to describe filters • After each convolutional layer we still have an “image” • Instead of 3 channels (r-g-b), 
 we have n - channels. 
 Each described by one of the learned filters
  • 8. Filters (or Kernels) Example of Edge Detector Example of Blurring Filter
  • 9. Pooling • Can condense information as filters pull details apart • With MaxPooling we take the local maximum activation as representative of the region. 
 Usually a 2x2 subsample • As we filter, precise location becomes less relevant • This condenses the amount of information 
 by ¼ per learned channel • BONUS: Net becomes tolerant to local perturbations in the data
  • 10. Traditional Feed-Forward Icing on the Cake • Flatten the filtered image 
 into one long 1 dimensional vector • Pass into a feed forward network • Out to classes -> to determine error • Learn like normal - backpropagation works on filter weights, just as it does on neuron weights
  • 13. Theano • Created by the 
 University of Montreal • Framework for 
 symbolic computation • Provides GPU support
 
 • Great Python libraries based on Theano: 
 Keras, Lasagne, PyLearn2 import numpy import theano.tensor as T x = T.dmatrix('x') y = T.dmatrix('y') z = x + y f = function([x, y], z)
  • 14. TensorFlow • Developed by a small startup in Moutainview • Used for 50 Google products • Used as part of AlphaGo (trained on TPUs*) • Designed for distributed learning problems • Growing ecosystem: TensorBoard, tflearn, scikit-flow import tensorflow as tf a = tf.placeholder("float") b = tf.placeholder("float") y = tf.mul(a, b) # multiply the symbolic variables with tf.Session() as sess: print("%f should equal 2.0" % sess.run(y, feed_dict={a: 1, b: 2})) print("%f should equal 9.0" % sess.run(y, feed_dict={a: 3, b: 3}))
  • 15. How to prepare your images for the classification?
  • 16. Normalize the image size • Use the pillow package in Python • For small size differences, squeeze images • For larger differences, resize images • Or use Keras’ pre-processing functions y, x = image.size y = x if x > y else y resized_image = Image.new(color_schema, (y, y), (255, )) try: resized_image.paste(image, image.getbbox()) except ValueError: continue resized_image = resized_image.resize(
 (resized_px, resized_px), Image.ANTIALIAS) resized_image.save(new_filename, 'jpeg', quality=90)
  • 17. Convert the images into matrices • Use the numpy package in Python • No magic, use numpy’s asarray method • Create a classification vector at the same time image = Image.open(directory + f) image.load() image_matrix = np.asarray(image, dtype="int32").T image_classification = 1 if animal == 'Cat/' else 0 data.append(image_matrix) classification.append(image_classification)
  • 18. Save the matrices in a reusable format • Pickle or numpy is your best friend • You can split the dataset into training/test set with `train_test_split`
 
 • Store matrices as compressed pickles (use numpy for large arrays) • Use compression! X_train, X_test, y_train, y_test = train_test_split( data, classification, test_size=0.20, random_state=42) np.savez_compressed('petsTrainingData.npz', X_train=X_train, X_test=X_test, y_train=y_train, y_test=y_test)
  • 19. How to assemble 
 a simple CNN 
 with Keras
  • 20. What is Keras? Why? • Excellent Python wrapper library for Theano • Supports TensorFlow too! • Growing TensorFlow support • Amazing documentation • Amazing community
  • 21. Steps 1. Setup your sequential model 2. Create a network structure 3. Set the “compile” parameters 4. Set the fit parameters
  • 22. Setup a sequential model • Sequential models allow you to define the network structure
 • Use model.add() to add layers to the neural network Model = Sequential() model.add(Convolution2D(64, 2, 2, border_mode='same'))
  • 23. Create your network structure • Keras provides various types of layers • Convolution2D • Convolution3D • Dense • Dropout • Activation • MaxPooling2D • etc. model.add(Convolution2D(64, 2, 2)) model.add(Activation(‘relu’)) model.add(MaxPooling2D(pool_size=(2, 2)))
  • 24. Set the “compile” parameters • Keras provides various options for optimizing your network • SGD • Adagrad • Adadelta • Etc. • Set the learning rate, momentum, etc. • Define your loss definition and metrics sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile( loss=‘categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
  • 25. Set the fit parameters • This is where the magic starts! • model.fit() allows you to define: • The batch size • Number of epochs • Whether you want to shuffle your training data • Your validation set • Your callbacks
 • Callbacks are amazing!
  • 26. Use Callbacks • Keras comes with various callbacks • ModelCheckpoint 
 allows saving the model parameters after every/best run • EarlyStopping 
 allows stopping the training if your training condition is met
 • Other callbacks: • LearningRateScheduler • TensorBoard • RemoteMonitor
  • 27. Faster, Faster … • GPU’s are your friends • Unlike traditional feed-forward nets, there are large parts of CNN’s that are parallel-izable! • As each neuron normally depends on the neuron before it and the error reported from the neuron after it, filters are different. • In a layer, each filter and each filter at each position are independent of each other. • So all of those computations can happen simultaneously. • And as all are simple matrix multiplications, we can make use of the 1000’s of cores on modern GPU’s
  • 28. Running on a GPU • Install proper dependencies (linux requires a few extra steps here) • Install Theano, Keras • Install CUDA (http://tleyden.github.io/blog/2015/11/22/cuda-7- dot-5-on-aws-gpu-instance-running-ubuntu-14-dot-04/) • Install cuDNN (requires registration with NVIDIA) • Configurations in ~/.theanorc • Set Theano Flags when running script (or in .theanorc) • Pre-configured AMI on AWS 
 (ami-a6ec17c6 in region US-west-2/Oregon)
  • 29. How does a training look like in action?
  • 31. What to do once the training is completed?
  • 33. Learning resources ConvNets • http://cs231n.stanford.edu/ • https://www.youtube.com/watch?v=bEUX_56Lojc • http://blog.keras.io/how-convolutional-neural-networks- see-the-world.html Keras • https://www.youtube.com/watch?v=Tp3SaRbql4k TensorFlow • http://learningtensorflow.com/examples/