Skip to content

Instantly share code, notes, and snippets.

@daniellerch
Created February 13, 2018 13:46
Show Gist options
  • Save daniellerch/b57b51e4bb5b7376ae4b57cbc88ec6f0 to your computer and use it in GitHub Desktop.
Save daniellerch/b57b51e4bb5b7376ae4b57cbc88ec6f0 to your computer and use it in GitHub Desktop.
Keras/MNIST
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Input, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import np_utils
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape+(1,))
x_test = x_test.reshape(x_test.shape+(1,))
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
inputs = Input(x_train.shape[1:])
x = inputs
x = Conv2D(32, (3, 3), activation='relu')(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Dropout(0.25)(x)
x = Flatten()(x)
x = Dense(128, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(10, activation='softmax')(x)
outputs = x
model = Model(inputs=inputs, outputs=outputs)
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=1,
validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print 'loss:', score[0], 'accuracy:', score[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment