In [1]:
from keras.datasets import mnist


Using TensorFlow backend.

In [2]:
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

In [3]:
train_images.shape


Out[3]:
(60000, 28, 28)

In [4]:
len(train_images)


Out[4]:
60000

In [7]:
train_labels


Out[7]:
array([5, 0, 4, ..., 5, 6, 8], dtype=uint8)

In [9]:
test_images.shape


Out[9]:
(10000, 28, 28)

In [10]:
len(test_images)


Out[10]:
10000

In [11]:
test_labels


Out[11]:
array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)

In [12]:
from keras import models
from keras import layers

In [13]:
network = models.Sequential()
network.add(layers.Dense(512, activation = "relu", input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation = "softmax"))

In [14]:
network.summary()


_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_1 (Dense)              (None, 512)               401920    
_________________________________________________________________
dense_2 (Dense)              (None, 10)                5130      
=================================================================
Total params: 407,050
Trainable params: 407,050
Non-trainable params: 0
_________________________________________________________________

In [15]:
network.compile(optimizer = "rmsprop", loss = "categorical_crossentropy", metrics = ["accuracy"])

In [16]:
train_images = train_images.reshape(60000, 28 * 28)
test_images = test_images.reshape(10000, 28 * 28)

train_images = train_images.astype("float32") / 255
test_images = test_images.astype("float32") / 255

In [17]:
from keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

In [18]:
network.fit(train_images, train_labels, epochs = 5, batch_size = 128)


Epoch 1/5
60000/60000 [==============================] - 7s - loss: 0.2571 - acc: 0.9250       
Epoch 2/5
60000/60000 [==============================] - 7s - loss: 0.1022 - acc: 0.9695     
Epoch 3/5
60000/60000 [==============================] - 7s - loss: 0.0695 - acc: 0.9790     
Epoch 4/5
60000/60000 [==============================] - 7s - loss: 0.0500 - acc: 0.9847     
Epoch 5/5
60000/60000 [==============================] - 7s - loss: 0.0382 - acc: 0.9886     
Out[18]:
<keras.callbacks.History at 0x7f092591e7b8>

In [19]:
test_loss, test_acc = network.evaluate(test_images, test_labels)
print("test accuracy", test_acc)


 9824/10000 [============================>.] - ETA: 0stest accuracy 0.9775

In [ ]: