Keras in less than 1 minute
Sep 20, 2019
Hmm. Neural Network you say?
In this tutorial I will introduce Keras in a bite sized chunks so that you can quickly get your boots off the ground and start prototyping with Keras.
What is Keras?
Keras has been designed as a high level library to build Deep Neural Networks. Although many compare it to Tensorflow, Caffe and etc, Keras uses either Tensorflow, CNTK or Theano in the backend to build the Neural Networks described by you.
The idea is as such. You purely describe your Neural Network in terms of your layer arrangement and how the layers connect, and the rest of it (neuron formation, BackPropogation, Training, everything).
How to use keras?
Keras has two styles/ways of programming to build a neural network, the sequential model and the Functional API model. We will cover the Sequential Model
The idea is as such, define a linear stack of layers and how they interconnect. Then compile and train it. The rest is taken care of by the framework.
Using Constructor or Shape Specifying
You can define the whole model in the contructor itself,
from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential([
Dense(32, input_shape=(784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])
or build the model by specifying each shape,
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
Compilation
Now the model needs to be compiled and more information needs to be specified,
- Optimizer to be used: This can be a string identifier of the optimizer, like
rmsprop
, oradagrad
. - Loss Function to be used: The loss fuction string indentifier, like ‘binary_crossentropy’, or
mse
. - Metrics List to be returned: For classification you would specify
metrics=["accuracy"]
For a simple binary classification this would appear like:
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
Training
Use the fit function to train the model.
# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=10, batch_size=32)
And that’s it! You have learned Keras! There are a few abstractions such as the Functional API which I have left out for simplicities sake, but you can now go forth and use Keras!
Share