SlideShare uma empresa Scribd logo
1 de 26
Baixar para ler offline
Keras: Deep Learning library for Theano and TensorFlow
Keras: Deep Learning library for Theano and TensorFlow
Alison Marczewski
UFMG
April 28, 2017
Alison Marczewski | UFMG | April 28, 2017 1 / 19
Keras: Deep Learning library for Theano and TensorFlow
Introduction
Fast prototyping
Support combination of convolutional and recurrent networks
CPU and GPU
Alison Marczewski | UFMG | April 28, 2017 2 / 19
Keras: Deep Learning library for Theano and TensorFlow
Guiding principles
User friendliness
Modularity
Easy extensibility
Work with Python
from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential([
Dense(32, input_shape=(784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])
Alison Marczewski | UFMG | April 28, 2017 3 / 19
Keras: Deep Learning library for Theano and TensorFlow
Core Layers
Dense(units, activation=None, use_bias=True) # Fully connected
Activation(activation) # linear, softmax, tanh...
Dropout(rate) # set values to zero
Flatten() # masks into vector
Reshape(target_shape)
Permute(dims) # Permute((2, 1), input_shape=(10, 64)) --> (64, 10)
RepeatVector(n) # RepeatVector(3, input_shape=(32,)) --> (3, 32)
ActivityRegularization(l1=0.0, l2=0.0)
# You can create your Layer
Alison Marczewski | UFMG | April 28, 2017 4 / 19
Keras: Deep Learning library for Theano and TensorFlow
Layer wrappers
from keras.layers.wrappers import *
# This wrapper allows to apply a layer to every temporal slice of an input.
TimeDistributed(layer)
# Sample
model = Sequential()
model.add(TimeDistributed(Dense(8), input_shape=(10, 16)))
# now model.output_shape == (None, 10, 8)
#Bidirectional wrapper for RNNs.
Bidirectional(layer, merge_mode='concat', weights=None)
Alison Marczewski | UFMG | April 28, 2017 5 / 19
Keras: Deep Learning library for Theano and TensorFlow
Preprocessings
For sequences: pad sequences, skipgrams...
For text: text to word, one hot, tokenizer
For image: ImageDataGenerator
Alison Marczewski | UFMG | April 28, 2017 6 / 19
Keras: Deep Learning library for Theano and TensorFlow
Compilation and Training
#--> Loss for a multi-class classification problem: 'categorical_crossentropy'
#--> Loss for a binary classification problem: 'binary_crossentropy'
#--> Loss for a mean squared error regression problem: 'mse'
#--> Metrics: binary_accuracy, categorical_accuracy...
# For custom metrics
import keras.backend as K
def mean_pred(y_true, y_pred):
return K.mean(y_pred)
# optimizer: SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam, TFOptimizer
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy', mean_pred])
# training model
model.fit(x_train, y_train, epochs=5, batch_size=32,
callbacks = [CALLBACK_LIST])
Alison Marczewski | UFMG | April 28, 2017 7 / 19
Keras: Deep Learning library for Theano and TensorFlow
Callbacks
from keras.callbacks import *
ModelCheckpoint(filepath, monitor='val_loss', verbose=0, save_best_only=False,
save_weights_only=False)
EarlyStopping(monitor='val_loss', min_delta=0, patience=0, verbose=0,
mode='auto')
LearningRateScheduler(schedule) #schedule: a function that takes an epoch
#index as input (integer, indexed from 0) and returns a new learning
#rate as output (float).
ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, verbose=0,
epsilon=0.0001, min_lr=0)
CSVLogger(filename, separator=',', append=False)
# You can create your callback
Alison Marczewski | UFMG | April 28, 2017 8 / 19
Keras: Deep Learning library for Theano and TensorFlow
Constraints
Functions from the constraints module allow setting constraints on
network parameters during optimization
max norm(max value=2, axis=0)
non neg
unit norm
from keras.constraints import maxnorm
# example
model.add(Dense(64, kernel_constraint=max_norm(2.)))
#--> kernel_constraint: for the main weights matrix
#--> bias_constraint: for the bias
Alison Marczewski | UFMG | April 28, 2017 9 / 19
Keras: Deep Learning library for Theano and TensorFlow
Utils
from keras.utils import *
# Conv a class vector to binary class matrix
# e.g: for use with categorical_crossentropy
to_categorical(y, num_classes=None)
plot_model(model, to_file='model.png', show_shapes=False,
show_layer_names=True)
Alison Marczewski | UFMG | April 28, 2017 10 / 19
Keras: Deep Learning library for Theano and TensorFlow
Applications
Some models are available for image classification with weights trained on
ImageNet: Xception, VGG16, VGG19, ResNet50, InceptionV3
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
model = ResNet50(weights='imagenet')
img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
# decode the results into a list of tuples (class, description, probability)
print('Predicted:', decode_predictions(preds, top=3)[0])
# Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225),
# (u'n01871265', u'tusker', 0.1122357),
# (u'n02504458', u'African_elephant', 0.061040461)]
Alison Marczewski | UFMG | April 28, 2017 11 / 19
Keras: Deep Learning library for Theano and TensorFlow
Working with several experiments/configs
What are the main differences among experiments?
Alison Marczewski | UFMG | April 28, 2017 12 / 19
Keras: Deep Learning library for Theano and TensorFlow
Working with several experiments/configs
What are the main differences among experiments?
data preprocessing
Alison Marczewski | UFMG | April 28, 2017 12 / 19
Keras: Deep Learning library for Theano and TensorFlow
Working with several experiments/configs
What are the main differences among experiments?
data preprocessing
models/configs
Alison Marczewski | UFMG | April 28, 2017 12 / 19
Keras: Deep Learning library for Theano and TensorFlow
Working with several experiments/configs
What are the main differences among experiments?
data preprocessing
models/configs: for each data preprocessing, there are one or more
configs
Alison Marczewski | UFMG | April 28, 2017 12 / 19
Keras: Deep Learning library for Theano and TensorFlow
Working with several experiments/configs
What are the main differences among experiments?
data preprocessing
module for loading dataset according to some parameters
models/configs: for each data preprocessing, there are one or more
configs
Alison Marczewski | UFMG | April 28, 2017 12 / 19
Keras: Deep Learning library for Theano and TensorFlow
Working with several experiments/configs
What are the main differences among experiments?
data preprocessing
module for loading dataset according to some parameters
models/configs: for each data preprocessing, there are one or more
configs
module for creating a model according to parameters
Alison Marczewski | UFMG | April 28, 2017 12 / 19
Keras: Deep Learning library for Theano and TensorFlow
Working with several experiments/configs
What are the main differences among experiments?
data preprocessing
module for loading dataset according to some parameters
models/configs: for each data preprocessing, there are one or more
configs
module for creating a model according to parameters
For each experiment: one data preprocessing with 1 or more
models/configs
Alison Marczewski | UFMG | April 28, 2017 12 / 19
Keras: Deep Learning library for Theano and TensorFlow
Working with several experiments/configs
What are the main differences among experiments?
data preprocessing
module for loading dataset according to some parameters
models/configs: for each data preprocessing, there are one or more
configs
module for creating a model according to parameters
For each experiment: one data preprocessing with 1 or more
models/configs
Instead of writing a python code for each one, loading a file with these
parameters
Alison Marczewski | UFMG | April 28, 2017 12 / 19
Keras: Deep Learning library for Theano and TensorFlow
Experiment/config file
# Basic example
experiment= {}
experiment['name']='experiment-01'
experiment['general'] = {'batch_size': 32, 'nb_epoch': 30,
'optimizer': 'adadelta'}
experiment['dataset'] = {'train': ['dataset_A', 'dataset_B'],
'percent_train': .8, 'percent_valid': .2, 'norm': 'unit_norm'}
experiment['classes'] = ['A', 'B', 'C']
experiment['configs'] = []
config = {}
config['name'] = 'config-01'
config['layers'] = []
config['layers'].append({'name': 'convolution_1', 'filter_length': 100,
'nb_filter': 128, 'activation': 'relu', 'border_mode': 'same'})
config['layers'].append({'name': 'maxpooling_1', 'pool_length': 200})
config['layers'].append({'name': 'dropout_1', 'p': 0.2})
config['layers'].append({'name': 'flatten_1'})
config['layers'].append({'name': 'dense_1', 'output_dim': 1000})
config['layers'].append({'name': 'dropout_2', 'p': 0.2})
config['layers'].append({'name': 'activation_1', 'activation': 'relu'})
experiment['configs'].append(config)
Alison Marczewski | UFMG | April 28, 2017 13 / 19
Keras: Deep Learning library for Theano and TensorFlow
Executing
if __name__ == '__main__':
exec(open(sys.argv[1]).read(), globals())
sys.stdout = Logger('experiments/{0}.log'.format(experiment['name']))
... = load_dataset(experiment['dataset'])
input_shape = X_train.shape[1:]
for config in experiment['configs']:
model = create_model(input_shape, config['layers'], experiment['classes'])
model.compile(loss='categorical_crossentropy',
optimizer=experiment['general'].get('optimizer', 'SGD'),
metrics=['accuracy'])
print(model.summary())
model.fit(...)
...
plot_model(model, '%s-%s'%(experiment['name'], config['name']))
Alison Marczewski | UFMG | April 28, 2017 14 / 19
Keras: Deep Learning library for Theano and TensorFlow
Create model I
def create_model(input_shape, layers, classes):
layers.append({'name': 'dense_final', 'output_dim': len(classes)})
layers.append({'name': 'activation_classifier',
'activation': 'softmax'})
model = Sequential()
for l in layers:
if len(model.layers) == 0:
l['input_shape'] = input_shape
print("layer:", l)
model.add(create_layer(**l))
return model
Alison Marczewski | UFMG | April 28, 2017 15 / 19
Keras: Deep Learning library for Theano and TensorFlow
Create model II
# Basic example
def create_layer(**kwargs):
name = kwargs.get('name')
if name.startswith('convolution'):
layer = Convolution1D(**kwargs)
elif name.startswith('maxpooling'):
layer = MaxPooling1D(**kwargs)
elif name.startswith('dropout'):
layer = Dropout(**kwargs)
elif name.startswith('flatten'):
layer = Flatten(**kwargs)
elif name.startswith('dense'):
layer = Dense(**kwargs)
elif name.startswith('activation'):
layer = Activation(**kwargs)
else:
raise "layer not supported yet", name
return layer
Alison Marczewski | UFMG | April 28, 2017 16 / 19
Keras: Deep Learning library for Theano and TensorFlow
Plot Model
Just for example
Alison Marczewski | UFMG | April 28, 2017 17 / 19
Keras: Deep Learning library for Theano and TensorFlow
Questions?
Alison Marczewski | UFMG | April 28, 2017 18 / 19
Keras: Deep Learning library for Theano and TensorFlow
Keras reference
https://keras.io
Alison Marczewski | UFMG | April 28, 2017 19 / 19

Mais conteúdo relacionado

Mais procurados

Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...MLconf
 
Dr. Erin LeDell, Machine Learning Scientist, H2O.ai at MLconf SEA - 5/20/16
Dr. Erin LeDell, Machine Learning Scientist, H2O.ai at MLconf SEA - 5/20/16Dr. Erin LeDell, Machine Learning Scientist, H2O.ai at MLconf SEA - 5/20/16
Dr. Erin LeDell, Machine Learning Scientist, H2O.ai at MLconf SEA - 5/20/16MLconf
 
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves MabialaDeep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves MabialaSpark Summit
 
Keras: Deep Learning Library for Python
Keras: Deep Learning Library for PythonKeras: Deep Learning Library for Python
Keras: Deep Learning Library for PythonRafi Khan
 
TensorFlow Tutorial Part1
TensorFlow Tutorial Part1TensorFlow Tutorial Part1
TensorFlow Tutorial Part1Sungjoon Choi
 
Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016
Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016
Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016MLconf
 
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016MLconf
 
Distributed Deep Learning on AWS with Apache MXNet
Distributed Deep Learning on AWS with Apache MXNetDistributed Deep Learning on AWS with Apache MXNet
Distributed Deep Learning on AWS with Apache MXNetAmazon Web Services
 
Hussein Mehanna, Engineering Director, ML Core - Facebook at MLconf ATL 2016
Hussein Mehanna, Engineering Director, ML Core - Facebook at MLconf ATL 2016Hussein Mehanna, Engineering Director, ML Core - Facebook at MLconf ATL 2016
Hussein Mehanna, Engineering Director, ML Core - Facebook at MLconf ATL 2016MLconf
 
Distributed implementation of a lstm on spark and tensorflow
Distributed implementation of a lstm on spark and tensorflowDistributed implementation of a lstm on spark and tensorflow
Distributed implementation of a lstm on spark and tensorflowEmanuel Di Nardo
 
Generating Sequences with Deep LSTMs & RNNS in julia
Generating Sequences with Deep LSTMs & RNNS in juliaGenerating Sequences with Deep LSTMs & RNNS in julia
Generating Sequences with Deep LSTMs & RNNS in juliaAndre Pemmelaar
 
MLConf 2016 SigOpt Talk by Scott Clark
MLConf 2016 SigOpt Talk by Scott ClarkMLConf 2016 SigOpt Talk by Scott Clark
MLConf 2016 SigOpt Talk by Scott ClarkSigOpt
 
Large Scale Deep Learning with TensorFlow
Large Scale Deep Learning with TensorFlow Large Scale Deep Learning with TensorFlow
Large Scale Deep Learning with TensorFlow Jen Aman
 
Synthetic dialogue generation with Deep Learning
Synthetic dialogue generation with Deep LearningSynthetic dialogue generation with Deep Learning
Synthetic dialogue generation with Deep LearningS N
 
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016MLconf
 
Diving into Deep Learning (Silicon Valley Code Camp 2017)
Diving into Deep Learning (Silicon Valley Code Camp 2017)Diving into Deep Learning (Silicon Valley Code Camp 2017)
Diving into Deep Learning (Silicon Valley Code Camp 2017)Oswald Campesato
 
Melanie Warrick, Deep Learning Engineer, Skymind.io at MLconf SF - 11/13/15
Melanie Warrick, Deep Learning Engineer, Skymind.io at MLconf SF - 11/13/15Melanie Warrick, Deep Learning Engineer, Skymind.io at MLconf SF - 11/13/15
Melanie Warrick, Deep Learning Engineer, Skymind.io at MLconf SF - 11/13/15MLconf
 
Le Song, Assistant Professor, College of Computing, Georgia Institute of Tech...
Le Song, Assistant Professor, College of Computing, Georgia Institute of Tech...Le Song, Assistant Professor, College of Computing, Georgia Institute of Tech...
Le Song, Assistant Professor, College of Computing, Georgia Institute of Tech...MLconf
 
Introduction to Neural Networks in Tensorflow
Introduction to Neural Networks in TensorflowIntroduction to Neural Networks in Tensorflow
Introduction to Neural Networks in TensorflowNicholas McClure
 
Modeling Electronic Health Records with Recurrent Neural Networks
Modeling Electronic Health Records with Recurrent Neural NetworksModeling Electronic Health Records with Recurrent Neural Networks
Modeling Electronic Health Records with Recurrent Neural NetworksJosh Patterson
 

Mais procurados (20)

Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
 
Dr. Erin LeDell, Machine Learning Scientist, H2O.ai at MLconf SEA - 5/20/16
Dr. Erin LeDell, Machine Learning Scientist, H2O.ai at MLconf SEA - 5/20/16Dr. Erin LeDell, Machine Learning Scientist, H2O.ai at MLconf SEA - 5/20/16
Dr. Erin LeDell, Machine Learning Scientist, H2O.ai at MLconf SEA - 5/20/16
 
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves MabialaDeep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
 
Keras: Deep Learning Library for Python
Keras: Deep Learning Library for PythonKeras: Deep Learning Library for Python
Keras: Deep Learning Library for Python
 
TensorFlow Tutorial Part1
TensorFlow Tutorial Part1TensorFlow Tutorial Part1
TensorFlow Tutorial Part1
 
Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016
Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016
Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016
 
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
 
Distributed Deep Learning on AWS with Apache MXNet
Distributed Deep Learning on AWS with Apache MXNetDistributed Deep Learning on AWS with Apache MXNet
Distributed Deep Learning on AWS with Apache MXNet
 
Hussein Mehanna, Engineering Director, ML Core - Facebook at MLconf ATL 2016
Hussein Mehanna, Engineering Director, ML Core - Facebook at MLconf ATL 2016Hussein Mehanna, Engineering Director, ML Core - Facebook at MLconf ATL 2016
Hussein Mehanna, Engineering Director, ML Core - Facebook at MLconf ATL 2016
 
Distributed implementation of a lstm on spark and tensorflow
Distributed implementation of a lstm on spark and tensorflowDistributed implementation of a lstm on spark and tensorflow
Distributed implementation of a lstm on spark and tensorflow
 
Generating Sequences with Deep LSTMs & RNNS in julia
Generating Sequences with Deep LSTMs & RNNS in juliaGenerating Sequences with Deep LSTMs & RNNS in julia
Generating Sequences with Deep LSTMs & RNNS in julia
 
MLConf 2016 SigOpt Talk by Scott Clark
MLConf 2016 SigOpt Talk by Scott ClarkMLConf 2016 SigOpt Talk by Scott Clark
MLConf 2016 SigOpt Talk by Scott Clark
 
Large Scale Deep Learning with TensorFlow
Large Scale Deep Learning with TensorFlow Large Scale Deep Learning with TensorFlow
Large Scale Deep Learning with TensorFlow
 
Synthetic dialogue generation with Deep Learning
Synthetic dialogue generation with Deep LearningSynthetic dialogue generation with Deep Learning
Synthetic dialogue generation with Deep Learning
 
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
 
Diving into Deep Learning (Silicon Valley Code Camp 2017)
Diving into Deep Learning (Silicon Valley Code Camp 2017)Diving into Deep Learning (Silicon Valley Code Camp 2017)
Diving into Deep Learning (Silicon Valley Code Camp 2017)
 
Melanie Warrick, Deep Learning Engineer, Skymind.io at MLconf SF - 11/13/15
Melanie Warrick, Deep Learning Engineer, Skymind.io at MLconf SF - 11/13/15Melanie Warrick, Deep Learning Engineer, Skymind.io at MLconf SF - 11/13/15
Melanie Warrick, Deep Learning Engineer, Skymind.io at MLconf SF - 11/13/15
 
Le Song, Assistant Professor, College of Computing, Georgia Institute of Tech...
Le Song, Assistant Professor, College of Computing, Georgia Institute of Tech...Le Song, Assistant Professor, College of Computing, Georgia Institute of Tech...
Le Song, Assistant Professor, College of Computing, Georgia Institute of Tech...
 
Introduction to Neural Networks in Tensorflow
Introduction to Neural Networks in TensorflowIntroduction to Neural Networks in Tensorflow
Introduction to Neural Networks in Tensorflow
 
Modeling Electronic Health Records with Recurrent Neural Networks
Modeling Electronic Health Records with Recurrent Neural NetworksModeling Electronic Health Records with Recurrent Neural Networks
Modeling Electronic Health Records with Recurrent Neural Networks
 

Semelhante a Basic ideas on keras framework

TechEvent Machine Learning
TechEvent Machine LearningTechEvent Machine Learning
TechEvent Machine LearningTrivadis
 
Scaling Deep Learning Algorithms on Extreme Scale Architectures
Scaling Deep Learning Algorithms on Extreme Scale ArchitecturesScaling Deep Learning Algorithms on Extreme Scale Architectures
Scaling Deep Learning Algorithms on Extreme Scale Architecturesinside-BigData.com
 
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...Databricks
 
Current clustering techniques
Current clustering techniquesCurrent clustering techniques
Current clustering techniquesPoonam Kshirsagar
 
HPCC Systems Engineering Summit Presentation - Collaborative Research with FA...
HPCC Systems Engineering Summit Presentation - Collaborative Research with FA...HPCC Systems Engineering Summit Presentation - Collaborative Research with FA...
HPCC Systems Engineering Summit Presentation - Collaborative Research with FA...HPCC Systems
 
The Flow of TensorFlow
The Flow of TensorFlowThe Flow of TensorFlow
The Flow of TensorFlowJeongkyu Shin
 
Predict saturated thickness using tensor board visualization
Predict saturated thickness using tensor board visualizationPredict saturated thickness using tensor board visualization
Predict saturated thickness using tensor board visualizationVinh Nguyen
 
MEX Vocabulary - A Lightweight Interchange Format for Machine Learning Experi...
MEX Vocabulary - A Lightweight Interchange Format for Machine Learning Experi...MEX Vocabulary - A Lightweight Interchange Format for Machine Learning Experi...
MEX Vocabulary - A Lightweight Interchange Format for Machine Learning Experi...Universität Leipzig
 
04-Data-Analysis-Overview.pptx
04-Data-Analysis-Overview.pptx04-Data-Analysis-Overview.pptx
04-Data-Analysis-Overview.pptxShree Shree
 
TensorFlow Tutorial | Deep Learning Using TensorFlow | TensorFlow Tutorial Py...
TensorFlow Tutorial | Deep Learning Using TensorFlow | TensorFlow Tutorial Py...TensorFlow Tutorial | Deep Learning Using TensorFlow | TensorFlow Tutorial Py...
TensorFlow Tutorial | Deep Learning Using TensorFlow | TensorFlow Tutorial Py...Edureka!
 
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017StampedeCon
 
Word Embedding Models & Support Vector Machines for Text Classification
Word Embedding Models & Support Vector Machines for Text ClassificationWord Embedding Models & Support Vector Machines for Text Classification
Word Embedding Models & Support Vector Machines for Text ClassificationNa'im Tyson
 
Scalable Deep Learning on AWS Using Apache MXNet - AWS Summit Tel Aviv 2017
Scalable Deep Learning on AWS Using Apache MXNet - AWS Summit Tel Aviv 2017Scalable Deep Learning on AWS Using Apache MXNet - AWS Summit Tel Aviv 2017
Scalable Deep Learning on AWS Using Apache MXNet - AWS Summit Tel Aviv 2017Amazon Web Services
 
deepnet-lourentzou.ppt
deepnet-lourentzou.pptdeepnet-lourentzou.ppt
deepnet-lourentzou.pptyang947066
 
Transfer learning with LTANN-MEM & NSA for solving multi-objective symbolic r...
Transfer learning with LTANN-MEM & NSA for solving multi-objective symbolic r...Transfer learning with LTANN-MEM & NSA for solving multi-objective symbolic r...
Transfer learning with LTANN-MEM & NSA for solving multi-objective symbolic r...Amr Kamel Deklel
 
IEEE Datamining 2016 Title and Abstract
IEEE  Datamining 2016 Title and AbstractIEEE  Datamining 2016 Title and Abstract
IEEE Datamining 2016 Title and Abstracttsysglobalsolutions
 
Haystack 2018 - Algorithmic Extraction of Keywords Concepts and Vocabularies
Haystack 2018 - Algorithmic Extraction of Keywords Concepts and VocabulariesHaystack 2018 - Algorithmic Extraction of Keywords Concepts and Vocabularies
Haystack 2018 - Algorithmic Extraction of Keywords Concepts and VocabulariesMax Irwin
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...Dr Arash Najmaei ( Phd., MBA, BSc)
 
PyCon Ukraine 2016: Maintaining a high load Python project for newcomers
PyCon Ukraine 2016: Maintaining a high load Python project for newcomersPyCon Ukraine 2016: Maintaining a high load Python project for newcomers
PyCon Ukraine 2016: Maintaining a high load Python project for newcomersViach Kakovskyi
 

Semelhante a Basic ideas on keras framework (20)

TechEvent Machine Learning
TechEvent Machine LearningTechEvent Machine Learning
TechEvent Machine Learning
 
1645 track 2 pafka
1645 track 2 pafka1645 track 2 pafka
1645 track 2 pafka
 
Scaling Deep Learning Algorithms on Extreme Scale Architectures
Scaling Deep Learning Algorithms on Extreme Scale ArchitecturesScaling Deep Learning Algorithms on Extreme Scale Architectures
Scaling Deep Learning Algorithms on Extreme Scale Architectures
 
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
 
Current clustering techniques
Current clustering techniquesCurrent clustering techniques
Current clustering techniques
 
HPCC Systems Engineering Summit Presentation - Collaborative Research with FA...
HPCC Systems Engineering Summit Presentation - Collaborative Research with FA...HPCC Systems Engineering Summit Presentation - Collaborative Research with FA...
HPCC Systems Engineering Summit Presentation - Collaborative Research with FA...
 
The Flow of TensorFlow
The Flow of TensorFlowThe Flow of TensorFlow
The Flow of TensorFlow
 
Predict saturated thickness using tensor board visualization
Predict saturated thickness using tensor board visualizationPredict saturated thickness using tensor board visualization
Predict saturated thickness using tensor board visualization
 
MEX Vocabulary - A Lightweight Interchange Format for Machine Learning Experi...
MEX Vocabulary - A Lightweight Interchange Format for Machine Learning Experi...MEX Vocabulary - A Lightweight Interchange Format for Machine Learning Experi...
MEX Vocabulary - A Lightweight Interchange Format for Machine Learning Experi...
 
04-Data-Analysis-Overview.pptx
04-Data-Analysis-Overview.pptx04-Data-Analysis-Overview.pptx
04-Data-Analysis-Overview.pptx
 
TensorFlow Tutorial | Deep Learning Using TensorFlow | TensorFlow Tutorial Py...
TensorFlow Tutorial | Deep Learning Using TensorFlow | TensorFlow Tutorial Py...TensorFlow Tutorial | Deep Learning Using TensorFlow | TensorFlow Tutorial Py...
TensorFlow Tutorial | Deep Learning Using TensorFlow | TensorFlow Tutorial Py...
 
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
 
Word Embedding Models & Support Vector Machines for Text Classification
Word Embedding Models & Support Vector Machines for Text ClassificationWord Embedding Models & Support Vector Machines for Text Classification
Word Embedding Models & Support Vector Machines for Text Classification
 
Scalable Deep Learning on AWS Using Apache MXNet - AWS Summit Tel Aviv 2017
Scalable Deep Learning on AWS Using Apache MXNet - AWS Summit Tel Aviv 2017Scalable Deep Learning on AWS Using Apache MXNet - AWS Summit Tel Aviv 2017
Scalable Deep Learning on AWS Using Apache MXNet - AWS Summit Tel Aviv 2017
 
deepnet-lourentzou.ppt
deepnet-lourentzou.pptdeepnet-lourentzou.ppt
deepnet-lourentzou.ppt
 
Transfer learning with LTANN-MEM & NSA for solving multi-objective symbolic r...
Transfer learning with LTANN-MEM & NSA for solving multi-objective symbolic r...Transfer learning with LTANN-MEM & NSA for solving multi-objective symbolic r...
Transfer learning with LTANN-MEM & NSA for solving multi-objective symbolic r...
 
IEEE Datamining 2016 Title and Abstract
IEEE  Datamining 2016 Title and AbstractIEEE  Datamining 2016 Title and Abstract
IEEE Datamining 2016 Title and Abstract
 
Haystack 2018 - Algorithmic Extraction of Keywords Concepts and Vocabularies
Haystack 2018 - Algorithmic Extraction of Keywords Concepts and VocabulariesHaystack 2018 - Algorithmic Extraction of Keywords Concepts and Vocabularies
Haystack 2018 - Algorithmic Extraction of Keywords Concepts and Vocabularies
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
 
PyCon Ukraine 2016: Maintaining a high load Python project for newcomers
PyCon Ukraine 2016: Maintaining a high load Python project for newcomersPyCon Ukraine 2016: Maintaining a high load Python project for newcomers
PyCon Ukraine 2016: Maintaining a high load Python project for newcomers
 

Último

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Último (20)

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 

Basic ideas on keras framework

  • 1. Keras: Deep Learning library for Theano and TensorFlow Keras: Deep Learning library for Theano and TensorFlow Alison Marczewski UFMG April 28, 2017 Alison Marczewski | UFMG | April 28, 2017 1 / 19
  • 2. Keras: Deep Learning library for Theano and TensorFlow Introduction Fast prototyping Support combination of convolutional and recurrent networks CPU and GPU Alison Marczewski | UFMG | April 28, 2017 2 / 19
  • 3. Keras: Deep Learning library for Theano and TensorFlow Guiding principles User friendliness Modularity Easy extensibility Work with Python from keras.models import Sequential from keras.layers import Dense, Activation model = Sequential([ Dense(32, input_shape=(784,)), Activation('relu'), Dense(10), Activation('softmax'), ]) Alison Marczewski | UFMG | April 28, 2017 3 / 19
  • 4. Keras: Deep Learning library for Theano and TensorFlow Core Layers Dense(units, activation=None, use_bias=True) # Fully connected Activation(activation) # linear, softmax, tanh... Dropout(rate) # set values to zero Flatten() # masks into vector Reshape(target_shape) Permute(dims) # Permute((2, 1), input_shape=(10, 64)) --> (64, 10) RepeatVector(n) # RepeatVector(3, input_shape=(32,)) --> (3, 32) ActivityRegularization(l1=0.0, l2=0.0) # You can create your Layer Alison Marczewski | UFMG | April 28, 2017 4 / 19
  • 5. Keras: Deep Learning library for Theano and TensorFlow Layer wrappers from keras.layers.wrappers import * # This wrapper allows to apply a layer to every temporal slice of an input. TimeDistributed(layer) # Sample model = Sequential() model.add(TimeDistributed(Dense(8), input_shape=(10, 16))) # now model.output_shape == (None, 10, 8) #Bidirectional wrapper for RNNs. Bidirectional(layer, merge_mode='concat', weights=None) Alison Marczewski | UFMG | April 28, 2017 5 / 19
  • 6. Keras: Deep Learning library for Theano and TensorFlow Preprocessings For sequences: pad sequences, skipgrams... For text: text to word, one hot, tokenizer For image: ImageDataGenerator Alison Marczewski | UFMG | April 28, 2017 6 / 19
  • 7. Keras: Deep Learning library for Theano and TensorFlow Compilation and Training #--> Loss for a multi-class classification problem: 'categorical_crossentropy' #--> Loss for a binary classification problem: 'binary_crossentropy' #--> Loss for a mean squared error regression problem: 'mse' #--> Metrics: binary_accuracy, categorical_accuracy... # For custom metrics import keras.backend as K def mean_pred(y_true, y_pred): return K.mean(y_pred) # optimizer: SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam, TFOptimizer model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy', mean_pred]) # training model model.fit(x_train, y_train, epochs=5, batch_size=32, callbacks = [CALLBACK_LIST]) Alison Marczewski | UFMG | April 28, 2017 7 / 19
  • 8. Keras: Deep Learning library for Theano and TensorFlow Callbacks from keras.callbacks import * ModelCheckpoint(filepath, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False) EarlyStopping(monitor='val_loss', min_delta=0, patience=0, verbose=0, mode='auto') LearningRateScheduler(schedule) #schedule: a function that takes an epoch #index as input (integer, indexed from 0) and returns a new learning #rate as output (float). ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, verbose=0, epsilon=0.0001, min_lr=0) CSVLogger(filename, separator=',', append=False) # You can create your callback Alison Marczewski | UFMG | April 28, 2017 8 / 19
  • 9. Keras: Deep Learning library for Theano and TensorFlow Constraints Functions from the constraints module allow setting constraints on network parameters during optimization max norm(max value=2, axis=0) non neg unit norm from keras.constraints import maxnorm # example model.add(Dense(64, kernel_constraint=max_norm(2.))) #--> kernel_constraint: for the main weights matrix #--> bias_constraint: for the bias Alison Marczewski | UFMG | April 28, 2017 9 / 19
  • 10. Keras: Deep Learning library for Theano and TensorFlow Utils from keras.utils import * # Conv a class vector to binary class matrix # e.g: for use with categorical_crossentropy to_categorical(y, num_classes=None) plot_model(model, to_file='model.png', show_shapes=False, show_layer_names=True) Alison Marczewski | UFMG | April 28, 2017 10 / 19
  • 11. Keras: Deep Learning library for Theano and TensorFlow Applications Some models are available for image classification with weights trained on ImageNet: Xception, VGG16, VGG19, ResNet50, InceptionV3 from keras.applications.resnet50 import ResNet50 from keras.preprocessing import image from keras.applications.resnet50 import preprocess_input, decode_predictions import numpy as np model = ResNet50(weights='imagenet') img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode the results into a list of tuples (class, description, probability) print('Predicted:', decode_predictions(preds, top=3)[0]) # Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), # (u'n01871265', u'tusker', 0.1122357), # (u'n02504458', u'African_elephant', 0.061040461)] Alison Marczewski | UFMG | April 28, 2017 11 / 19
  • 12. Keras: Deep Learning library for Theano and TensorFlow Working with several experiments/configs What are the main differences among experiments? Alison Marczewski | UFMG | April 28, 2017 12 / 19
  • 13. Keras: Deep Learning library for Theano and TensorFlow Working with several experiments/configs What are the main differences among experiments? data preprocessing Alison Marczewski | UFMG | April 28, 2017 12 / 19
  • 14. Keras: Deep Learning library for Theano and TensorFlow Working with several experiments/configs What are the main differences among experiments? data preprocessing models/configs Alison Marczewski | UFMG | April 28, 2017 12 / 19
  • 15. Keras: Deep Learning library for Theano and TensorFlow Working with several experiments/configs What are the main differences among experiments? data preprocessing models/configs: for each data preprocessing, there are one or more configs Alison Marczewski | UFMG | April 28, 2017 12 / 19
  • 16. Keras: Deep Learning library for Theano and TensorFlow Working with several experiments/configs What are the main differences among experiments? data preprocessing module for loading dataset according to some parameters models/configs: for each data preprocessing, there are one or more configs Alison Marczewski | UFMG | April 28, 2017 12 / 19
  • 17. Keras: Deep Learning library for Theano and TensorFlow Working with several experiments/configs What are the main differences among experiments? data preprocessing module for loading dataset according to some parameters models/configs: for each data preprocessing, there are one or more configs module for creating a model according to parameters Alison Marczewski | UFMG | April 28, 2017 12 / 19
  • 18. Keras: Deep Learning library for Theano and TensorFlow Working with several experiments/configs What are the main differences among experiments? data preprocessing module for loading dataset according to some parameters models/configs: for each data preprocessing, there are one or more configs module for creating a model according to parameters For each experiment: one data preprocessing with 1 or more models/configs Alison Marczewski | UFMG | April 28, 2017 12 / 19
  • 19. Keras: Deep Learning library for Theano and TensorFlow Working with several experiments/configs What are the main differences among experiments? data preprocessing module for loading dataset according to some parameters models/configs: for each data preprocessing, there are one or more configs module for creating a model according to parameters For each experiment: one data preprocessing with 1 or more models/configs Instead of writing a python code for each one, loading a file with these parameters Alison Marczewski | UFMG | April 28, 2017 12 / 19
  • 20. Keras: Deep Learning library for Theano and TensorFlow Experiment/config file # Basic example experiment= {} experiment['name']='experiment-01' experiment['general'] = {'batch_size': 32, 'nb_epoch': 30, 'optimizer': 'adadelta'} experiment['dataset'] = {'train': ['dataset_A', 'dataset_B'], 'percent_train': .8, 'percent_valid': .2, 'norm': 'unit_norm'} experiment['classes'] = ['A', 'B', 'C'] experiment['configs'] = [] config = {} config['name'] = 'config-01' config['layers'] = [] config['layers'].append({'name': 'convolution_1', 'filter_length': 100, 'nb_filter': 128, 'activation': 'relu', 'border_mode': 'same'}) config['layers'].append({'name': 'maxpooling_1', 'pool_length': 200}) config['layers'].append({'name': 'dropout_1', 'p': 0.2}) config['layers'].append({'name': 'flatten_1'}) config['layers'].append({'name': 'dense_1', 'output_dim': 1000}) config['layers'].append({'name': 'dropout_2', 'p': 0.2}) config['layers'].append({'name': 'activation_1', 'activation': 'relu'}) experiment['configs'].append(config) Alison Marczewski | UFMG | April 28, 2017 13 / 19
  • 21. Keras: Deep Learning library for Theano and TensorFlow Executing if __name__ == '__main__': exec(open(sys.argv[1]).read(), globals()) sys.stdout = Logger('experiments/{0}.log'.format(experiment['name'])) ... = load_dataset(experiment['dataset']) input_shape = X_train.shape[1:] for config in experiment['configs']: model = create_model(input_shape, config['layers'], experiment['classes']) model.compile(loss='categorical_crossentropy', optimizer=experiment['general'].get('optimizer', 'SGD'), metrics=['accuracy']) print(model.summary()) model.fit(...) ... plot_model(model, '%s-%s'%(experiment['name'], config['name'])) Alison Marczewski | UFMG | April 28, 2017 14 / 19
  • 22. Keras: Deep Learning library for Theano and TensorFlow Create model I def create_model(input_shape, layers, classes): layers.append({'name': 'dense_final', 'output_dim': len(classes)}) layers.append({'name': 'activation_classifier', 'activation': 'softmax'}) model = Sequential() for l in layers: if len(model.layers) == 0: l['input_shape'] = input_shape print("layer:", l) model.add(create_layer(**l)) return model Alison Marczewski | UFMG | April 28, 2017 15 / 19
  • 23. Keras: Deep Learning library for Theano and TensorFlow Create model II # Basic example def create_layer(**kwargs): name = kwargs.get('name') if name.startswith('convolution'): layer = Convolution1D(**kwargs) elif name.startswith('maxpooling'): layer = MaxPooling1D(**kwargs) elif name.startswith('dropout'): layer = Dropout(**kwargs) elif name.startswith('flatten'): layer = Flatten(**kwargs) elif name.startswith('dense'): layer = Dense(**kwargs) elif name.startswith('activation'): layer = Activation(**kwargs) else: raise "layer not supported yet", name return layer Alison Marczewski | UFMG | April 28, 2017 16 / 19
  • 24. Keras: Deep Learning library for Theano and TensorFlow Plot Model Just for example Alison Marczewski | UFMG | April 28, 2017 17 / 19
  • 25. Keras: Deep Learning library for Theano and TensorFlow Questions? Alison Marczewski | UFMG | April 28, 2017 18 / 19
  • 26. Keras: Deep Learning library for Theano and TensorFlow Keras reference https://keras.io Alison Marczewski | UFMG | April 28, 2017 19 / 19