In [1]:
from keras.datasets import mnist

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


Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz
11493376/11490434 [==============================] - 6s 1us/step

In [3]:
train_images.shape


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

In [4]:
len(train_labels)


Out[4]:
60000

In [5]:
train_labels


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

In [6]:
test_images.shape


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

In [7]:
len(test_labels)


Out[7]:
10000

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

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

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

In [11]:
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype("float32") / 255

test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype("float32") / 255

In [12]:
from keras.utils import to_categorical

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

In [13]:
train_labels


Out[13]:
array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 1.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       ..., 
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  1.,  0.]])

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


Epoch 1/5
60000/60000 [==============================] - 72s 1ms/step - loss: 0.2574 - acc: 0.9256
Epoch 2/5
60000/60000 [==============================] - 2s 29us/step - loss: 0.1030 - acc: 0.9693
Epoch 3/5
60000/60000 [==============================] - 2s 31us/step - loss: 0.0672 - acc: 0.9799
Epoch 4/5
60000/60000 [==============================] - 2s 31us/step - loss: 0.0497 - acc: 0.9849
Epoch 5/5
60000/60000 [==============================] - 2s 30us/step - loss: 0.0376 - acc: 0.9887
Out[14]:
<keras.callbacks.History at 0x1837d691470>

In [15]:
test_loss, test_acc = net.evaluate(test_images, test_labels)


10000/10000 [==============================] - 0s 47us/step

In [16]:
print("test_acc", test_acc)


test_acc 0.98

In [ ]: