SlideShare a Scribd company logo
1 of 11
Learning _______
by building Dogs-vs-Cats image classifier
Jian Wu
Reading Group
AI & Machine Learning Lab
Samsung SDSRA
Keras Overview
● Keras is a high-level neural network API, written in Python
● Built on top of either Theano or TensorFlow
● Most powerful & easy to use for developing and evaluating deep neural network
models
Ref: https://keras.io
Keras is a core package in TensorFlow 1.4
Ref: https://developers.googleblog.com/2017/11/announcing-tensorflow-r14.html
Deep Learning and Convolutional Neural Network
for Image Classification
Ref: https://deeplearning.ai
Convolutional Neural Network in a Nutshell
1. Convolution Filter/Operator
2. Max Pooling or Downsampling
The purpose of the convolution filter is to
extract features from the input image, it
preserves the spatial relationship between
pixels by learning image features using small
squares of input data
Max pooling or downsampling is to reduces
the dimensionality of each feature map but
retains the most important information
Ref: https://www.coursera.org/learn/convolutional-neural-networks/home/welcome
Convolutional Neural Network to classify dogs vs cats
Kaggle Dogs vs. Cats competition with labeled data set
Using CNN to classify dogs vs cats
This training data set contains 12500
labeled dog images and 12500 labeled cat
images, total 25000 images
Ref: https://www.kaggle.com/c/dogs-vs-cats
Get Started with Keras (tf.keras)
Keras is a model-level deep learning framework, which provides high-level API to construct neural
network model through layers, there are two ways to build a nn model in Keras:
The simplest type of model is the Sequential model, a linear stack of layers:
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))
The Keras functional API is used to define complex models, such as model(s) with shared layers and
multi-output models:
inputs = Input(shape=(784,))
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)
model = Model(inputs=inputs, outputs=predictions)
Processing image data with ImageDataGenerator
For image classification task, it is best practice to augment your training image data, producing more
image data and preventing overfitting. Keras ImageDataGenerator is a simple and powerful tool to
process and augment image data, supporting :
-- batch and iterative processing image data just-in-time
-- zoom image, rescale/normalize image, shear image, flip image horizontally and vertically, … ...
Processing/Augmenting image data for training and validation:
train_datagen = ImageDataGenerator(rescale=(1.0/255), shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
train_generator = train_datagen.flow_from_directory(train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_datagen = ImageDataGenerator(rescale=(1.0/255))
validation_generator = validation_datagen.flow_from_directory(validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
Building CNN model with Functional model API
With TensorFlow 1.4, it is recommended to use Keras Functional model API to build neural network
model, for dogs-vs-cats image classification, we are building a CNN model with three convolution
layers with max pooling plus two dense layers with dropout:
def build_cnn_model(input_shape):
input_image = Input(shape=input_shape)
conv_1 = Conv2D(32, (3, 3), activation='relu')(input_image)
pool_1 = MaxPooling2D((2, 2))(conv_1)
conv_2 = Conv2D(32, (3, 3), activation='relu')(pool_1)
pool_2 = MaxPooling2D((2, 2))(conv_2)
conv_3 = Conv2D(64, (3, 3), activation='relu')(pool_2)
pool_3 = MaxPooling2D((2, 2))(conv_3)
flatten = Flatten()(pool_3)
dense = Dense(64, activation='relu')(flatten)
dropout = Dropout(0.5)(dense)
prediction = Dense(1, activation='sigmoid')(dropout)
cnn_model = Model(inputs=input_image, outputs=prediction)
cnn_model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
return cnn_model
MaxPooling2D
Dense
Convolution2D
Convolution2D
MaxPooling2D
Convolution2D
MaxPooling2D
Flatten
Dense
Training CNN model with labeled dogs-vs-cats image set
With configured ImageDataGenerator and designed CNN Model, we can start training using Kaggle
labeled dogs-vs-cats image set and monitor the training with TensorBoard:
train_steps = nb_train_samples//batch_size
validation_steps =
nb_validation_samples//batch_size
tensorboard = TensorBoard(log_dir="summary_logs",
write_graph=True)
cnn_model = build_cnn_model(input_shape)
cnn_model.fit_generator(
train_generator,
steps_per_epoch=train_steps,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_steps,
callbacks=[tensorboard])
Save and reload trained CNN model to make predictions
Keras provides API to make prediction with trained model, it also provides API to save trained
weights of neural network model to HD5 file, the HD5 weight file can be used in production to reload
pre-trained model by reading trained weights from HD5 file and make predictions :
# save trained model weights
cnn_model.save(model_file)
# reload trained model at production site
cnn_model.load_weights(model_file)
# make predictions with pre-trained model
image_data_generator = ImageDataGenerator(rescale=(1.0 / 255))
test_generator = image_data_generator.flow_from_directory(
test_data_dir,
target_size=(img_width, img_height),
batch_size=5,
class_mode=None, # only data, no labels
shuffle=False
)
predictions = cnn_model.predict_generator(test_generator, steps=2)

More Related Content

What's hot

Reinforcement learning Research experiments OpenAI
Reinforcement learning Research experiments OpenAIReinforcement learning Research experiments OpenAI
Reinforcement learning Research experiments OpenAI
Raouf KESKES
 
Learn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
Learn to Build an App to Find Similar Images using Deep Learning- Piotr TeterwakLearn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
Learn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
PyData
 

What's hot (20)

C3 w3
C3 w3C3 w3
C3 w3
 
Course 2 Machine Learning Data LifeCycle in Production - Week 1
Course 2   Machine Learning Data LifeCycle in Production - Week 1Course 2   Machine Learning Data LifeCycle in Production - Week 1
Course 2 Machine Learning Data LifeCycle in Production - Week 1
 
“DNN Training Data: How to Know What You Need and How to Get It,” a Presentat...
“DNN Training Data: How to Know What You Need and How to Get It,” a Presentat...“DNN Training Data: How to Know What You Need and How to Get It,” a Presentat...
“DNN Training Data: How to Know What You Need and How to Get It,” a Presentat...
 
Iaetsd multi-view and multi band face recognition
Iaetsd multi-view and multi band face recognitionIaetsd multi-view and multi band face recognition
Iaetsd multi-view and multi band face recognition
 
Reinforcement learning Research experiments OpenAI
Reinforcement learning Research experiments OpenAIReinforcement learning Research experiments OpenAI
Reinforcement learning Research experiments OpenAI
 
Using Deep Learning to Find Similar Dresses
Using Deep Learning to Find Similar DressesUsing Deep Learning to Find Similar Dresses
Using Deep Learning to Find Similar Dresses
 
Higgs Boson Challenge
Higgs Boson ChallengeHiggs Boson Challenge
Higgs Boson Challenge
 
C3 w4
C3 w4C3 w4
C3 w4
 
Feature extraction for classifying students based on theirac ademic performance
Feature extraction for classifying students based on theirac ademic performanceFeature extraction for classifying students based on theirac ademic performance
Feature extraction for classifying students based on theirac ademic performance
 
Machine Learning Fundamentals
Machine Learning FundamentalsMachine Learning Fundamentals
Machine Learning Fundamentals
 
Deep learning summary
Deep learning summaryDeep learning summary
Deep learning summary
 
Introduction to machine learning
Introduction to machine learningIntroduction to machine learning
Introduction to machine learning
 
Delayed Rewards in the context of Reinforcement Learning based Recommender ...
Delayed Rewards in the context of Reinforcement Learning based Recommender ...Delayed Rewards in the context of Reinforcement Learning based Recommender ...
Delayed Rewards in the context of Reinforcement Learning based Recommender ...
 
Software defect estimation using machine learning algorithms
Software defect estimation using machine learning algorithmsSoftware defect estimation using machine learning algorithms
Software defect estimation using machine learning algorithms
 
Hacking Predictive Modeling - RoadSec 2018
Hacking Predictive Modeling - RoadSec 2018Hacking Predictive Modeling - RoadSec 2018
Hacking Predictive Modeling - RoadSec 2018
 
RankSRGAN
RankSRGANRankSRGAN
RankSRGAN
 
Learn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
Learn to Build an App to Find Similar Images using Deep Learning- Piotr TeterwakLearn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
Learn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
 
SigOpt for Machine Learning and AI
SigOpt for Machine Learning and AISigOpt for Machine Learning and AI
SigOpt for Machine Learning and AI
 
Workshop - Introduction to Machine Learning with R
Workshop - Introduction to Machine Learning with RWorkshop - Introduction to Machine Learning with R
Workshop - Introduction to Machine Learning with R
 
Tuning the Untunable - Insights on Deep Learning Optimization
Tuning the Untunable - Insights on Deep Learning OptimizationTuning the Untunable - Insights on Deep Learning Optimization
Tuning the Untunable - Insights on Deep Learning Optimization
 

Similar to Learning keras by building dogs-vs-cats image classifier

AIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdfAIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdf
ssuserb4d806
 

Similar to Learning keras by building dogs-vs-cats image classifier (20)

IRJET- Automatic Object Sorting using Deep Learning
IRJET- Automatic Object Sorting using Deep LearningIRJET- Automatic Object Sorting using Deep Learning
IRJET- Automatic Object Sorting using Deep Learning
 
Metaphorical Analysis of diseases in Tomato leaves using Deep Learning Algori...
Metaphorical Analysis of diseases in Tomato leaves using Deep Learning Algori...Metaphorical Analysis of diseases in Tomato leaves using Deep Learning Algori...
Metaphorical Analysis of diseases in Tomato leaves using Deep Learning Algori...
 
IRJET- Object Detection in an Image using Convolutional Neural Network
IRJET- Object Detection in an Image using Convolutional Neural NetworkIRJET- Object Detection in an Image using Convolutional Neural Network
IRJET- Object Detection in an Image using Convolutional Neural Network
 
“Practical Guide to Implementing Deep Neural Network Inferencing at the Edge,...
“Practical Guide to Implementing Deep Neural Network Inferencing at the Edge,...“Practical Guide to Implementing Deep Neural Network Inferencing at the Edge,...
“Practical Guide to Implementing Deep Neural Network Inferencing at the Edge,...
 
AI Powered Drones
AI Powered DronesAI Powered Drones
AI Powered Drones
 
A Tour of Tensorflow's APIs
A Tour of Tensorflow's APIsA Tour of Tensorflow's APIs
A Tour of Tensorflow's APIs
 
AWS re:Invent 2018 - AIM401 - Deep Learning using Tensorflow
AWS re:Invent 2018 - AIM401 - Deep Learning using TensorflowAWS re:Invent 2018 - AIM401 - Deep Learning using Tensorflow
AWS re:Invent 2018 - AIM401 - Deep Learning using Tensorflow
 
[REPEAT] Deep Learning Applications Using TensorFlow (AIM401-R) - AWS re:Inve...
[REPEAT] Deep Learning Applications Using TensorFlow (AIM401-R) - AWS re:Inve...[REPEAT] Deep Learning Applications Using TensorFlow (AIM401-R) - AWS re:Inve...
[REPEAT] Deep Learning Applications Using TensorFlow (AIM401-R) - AWS re:Inve...
 
Tensor flow
Tensor flowTensor flow
Tensor flow
 
Viktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceViktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning Service
 
Alluxio Webinar - Maximize GPU Utilization for Model Training
Alluxio Webinar - Maximize GPU Utilization for Model TrainingAlluxio Webinar - Maximize GPU Utilization for Model Training
Alluxio Webinar - Maximize GPU Utilization for Model Training
 
Image Classification using Deep Learning
Image Classification using Deep LearningImage Classification using Deep Learning
Image Classification using Deep Learning
 
DLT UNIT-3.docx
DLT  UNIT-3.docxDLT  UNIT-3.docx
DLT UNIT-3.docx
 
AIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdfAIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdf
 
IRJET- Mango Classification using Convolutional Neural Networks
IRJET- Mango Classification using Convolutional Neural NetworksIRJET- Mango Classification using Convolutional Neural Networks
IRJET- Mango Classification using Convolutional Neural Networks
 
An Introduction to Amazon SageMaker (October 2018)
An Introduction to Amazon SageMaker (October 2018)An Introduction to Amazon SageMaker (October 2018)
An Introduction to Amazon SageMaker (October 2018)
 
B4UConference_machine learning_deeplearning
B4UConference_machine learning_deeplearningB4UConference_machine learning_deeplearning
B4UConference_machine learning_deeplearning
 
Detection of medical instruments project- PART 1
Detection of medical instruments project- PART 1Detection of medical instruments project- PART 1
Detection of medical instruments project- PART 1
 
Amazon SageMaker 內建機器學習演算法 (Level 400)
Amazon SageMaker 內建機器學習演算法 (Level 400)Amazon SageMaker 內建機器學習演算法 (Level 400)
Amazon SageMaker 內建機器學習演算法 (Level 400)
 
Enhance your java applications with deep learning using deep netts
Enhance your java applications with deep learning using deep nettsEnhance your java applications with deep learning using deep netts
Enhance your java applications with deep learning using deep netts
 

Recently uploaded

Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
amitlee9823
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
amitlee9823
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
shivangimorya083
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
shivangimorya083
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...
shambhavirathore45
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
shivangimorya083
 
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
amitlee9823
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort ServiceBDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
 
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
 

Learning keras by building dogs-vs-cats image classifier

  • 1. Learning _______ by building Dogs-vs-Cats image classifier Jian Wu Reading Group AI & Machine Learning Lab Samsung SDSRA
  • 2. Keras Overview ● Keras is a high-level neural network API, written in Python ● Built on top of either Theano or TensorFlow ● Most powerful & easy to use for developing and evaluating deep neural network models Ref: https://keras.io
  • 3. Keras is a core package in TensorFlow 1.4 Ref: https://developers.googleblog.com/2017/11/announcing-tensorflow-r14.html
  • 4. Deep Learning and Convolutional Neural Network for Image Classification Ref: https://deeplearning.ai
  • 5. Convolutional Neural Network in a Nutshell 1. Convolution Filter/Operator 2. Max Pooling or Downsampling The purpose of the convolution filter is to extract features from the input image, it preserves the spatial relationship between pixels by learning image features using small squares of input data Max pooling or downsampling is to reduces the dimensionality of each feature map but retains the most important information Ref: https://www.coursera.org/learn/convolutional-neural-networks/home/welcome
  • 6. Convolutional Neural Network to classify dogs vs cats Kaggle Dogs vs. Cats competition with labeled data set Using CNN to classify dogs vs cats This training data set contains 12500 labeled dog images and 12500 labeled cat images, total 25000 images Ref: https://www.kaggle.com/c/dogs-vs-cats
  • 7. Get Started with Keras (tf.keras) Keras is a model-level deep learning framework, which provides high-level API to construct neural network model through layers, there are two ways to build a nn model in Keras: The simplest type of model is the Sequential model, a linear stack of layers: model = Sequential() model.add(Dense(32, input_dim=784)) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('softmax')) The Keras functional API is used to define complex models, such as model(s) with shared layers and multi-output models: inputs = Input(shape=(784,)) x = Dense(64, activation='relu')(inputs) x = Dense(64, activation='relu')(x) predictions = Dense(10, activation='softmax')(x) model = Model(inputs=inputs, outputs=predictions)
  • 8. Processing image data with ImageDataGenerator For image classification task, it is best practice to augment your training image data, producing more image data and preventing overfitting. Keras ImageDataGenerator is a simple and powerful tool to process and augment image data, supporting : -- batch and iterative processing image data just-in-time -- zoom image, rescale/normalize image, shear image, flip image horizontally and vertically, … ... Processing/Augmenting image data for training and validation: train_datagen = ImageDataGenerator(rescale=(1.0/255), shear_range=0.2, zoom_range=0.2, horizontal_flip=True) train_generator = train_datagen.flow_from_directory(train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary') validation_datagen = ImageDataGenerator(rescale=(1.0/255)) validation_generator = validation_datagen.flow_from_directory(validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary')
  • 9. Building CNN model with Functional model API With TensorFlow 1.4, it is recommended to use Keras Functional model API to build neural network model, for dogs-vs-cats image classification, we are building a CNN model with three convolution layers with max pooling plus two dense layers with dropout: def build_cnn_model(input_shape): input_image = Input(shape=input_shape) conv_1 = Conv2D(32, (3, 3), activation='relu')(input_image) pool_1 = MaxPooling2D((2, 2))(conv_1) conv_2 = Conv2D(32, (3, 3), activation='relu')(pool_1) pool_2 = MaxPooling2D((2, 2))(conv_2) conv_3 = Conv2D(64, (3, 3), activation='relu')(pool_2) pool_3 = MaxPooling2D((2, 2))(conv_3) flatten = Flatten()(pool_3) dense = Dense(64, activation='relu')(flatten) dropout = Dropout(0.5)(dense) prediction = Dense(1, activation='sigmoid')(dropout) cnn_model = Model(inputs=input_image, outputs=prediction) cnn_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) return cnn_model MaxPooling2D Dense Convolution2D Convolution2D MaxPooling2D Convolution2D MaxPooling2D Flatten Dense
  • 10. Training CNN model with labeled dogs-vs-cats image set With configured ImageDataGenerator and designed CNN Model, we can start training using Kaggle labeled dogs-vs-cats image set and monitor the training with TensorBoard: train_steps = nb_train_samples//batch_size validation_steps = nb_validation_samples//batch_size tensorboard = TensorBoard(log_dir="summary_logs", write_graph=True) cnn_model = build_cnn_model(input_shape) cnn_model.fit_generator( train_generator, steps_per_epoch=train_steps, epochs=epochs, validation_data=validation_generator, validation_steps=validation_steps, callbacks=[tensorboard])
  • 11. Save and reload trained CNN model to make predictions Keras provides API to make prediction with trained model, it also provides API to save trained weights of neural network model to HD5 file, the HD5 weight file can be used in production to reload pre-trained model by reading trained weights from HD5 file and make predictions : # save trained model weights cnn_model.save(model_file) # reload trained model at production site cnn_model.load_weights(model_file) # make predictions with pre-trained model image_data_generator = ImageDataGenerator(rescale=(1.0 / 255)) test_generator = image_data_generator.flow_from_directory( test_data_dir, target_size=(img_width, img_height), batch_size=5, class_mode=None, # only data, no labels shuffle=False ) predictions = cnn_model.predict_generator(test_generator, steps=2)