Keras Cheatsheet:
Python Deep Learning Tutorial
This cheatsheet will take you step-by-step through training a convolutional neural network in Python using the
famous MNIST dataset for handwritten digits classification. Our classifier will boast over 99% accuracy.
Keras is our recommended library for deep learning in Python, especially for beginners. Its minimalist, modular
approach makes it a breeze to get deep neural networks up and running.
To see the most up-to-date full tutorial, as well as installation instructions, visit the online tutorial at
[Link].
SETUP Preprocess class labels
Make sure you have the following installed on your computer: Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)
• Python 2.7+ or Python 3
• SciPy with NumPy
• Matplotlib (Optional, recommended for exploratory analysis)
• Theano* Define model architecture
*note: TensorFlow is also supported (as an alternative to Theano), but we model = Sequential()
stick with Theano to keep it simple. The main difference is that you’ll need
to reshape the data slightly differently before feeding it to your network.
[Link](Convolution2D(32, 3, 3, activation=’relu’,
input_shape=(1,28,28)))
Import libraries and modules [Link](Convolution2D(32, 3, 3, activation=’relu’))
import numpy as np
[Link](MaxPooling2D(pool_size=(2,2)))
[Link](123) # for reproducibility
[Link](Dropout(0.25))
from [Link] import Sequential
[Link](Flatten())
from [Link] import Dense, Dropout, Activation, Flatten
[Link](Dense(128, activation=’relu’))
from [Link] import Convolution2D, MaxPooling2D
[Link](Dropout(0.5))
from [Link] import np_utils
[Link](Dense(10, activation=’softmax’))
from [Link] import mnist
Compile model
Load pre-shuffled MNIST data [Link](loss=’categorical_crossentropy’,
into train and test sets optimizer=’adam’,
(X_train, y_train), (X_test, y_test) = mnist.load_data() metrics=[‘accuracy’])
Preprocess input data Fit model on training data
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
[Link](X_train, Y_train,
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
batch_size=32, nb_epoch=10, verbose=1)
X_train = X_train.astype(‘float32’)
X_test = X_test.astype(‘float32’)
X_train /= 255
Evaluate model on test data
score = [Link](X_test, Y_test, verbose=0)
X_test /= 255
To see the most up-to-date full tutorial, explanations, and additional context, visit the online tutorial at [Link].
We also have plenty of other tutorials and guides.
[Link]