from keras.datasets import mnist
from matplotlib import pyplot as plt
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
(x_train, y_train), (x_validation,y_validation) = mnist.load_data()
plt.subplot(221)
plt.imshow(x_train[0], cmap=plt.get_cmap('gray'))
plt.subplot(222)
plt.imshow(x_train[1], cmap=plt.get_cmap('gray'))
plt.subplot(223)
plt.imshow(x_train[2], cmap=plt.get_cmap('gray'))
plt.subplot(224)
plt.imshow(x_train[3], cmap=plt.get_cmap('gray'))
plt.show()
seed = 7
np.random.seed()
Using TensorFlow backend.
<Figure size 640x480 with 4 Axes>
num_pixels=x_train.shape[1]*x_train.shape[2]
print(x_train.shape[0])
print(num_pixels)
60000
784
x_train = x_train.reshape(x_train.shape[0],num_pixels).astype('float32')
x_validation = x_validation.reshape(x_validation.shape[0],num_pixels).astype('float32')
x_train = x_train/255
x_validation = x_validation/255
y_train = np_utils.to_categorical(y_train)
y_validation = np_utils.to_categorical(y_validation)
num_classes = y_validation.shape[1]
print(num_classes)
10
def create_model():
model = Sequential()
model.add(Dense(units=num_pixels, input_dim = num_pixels,kernel_initializer='normal',activation='relu'))
model.add(Dense(units=784,kernel_initializer='normal',activation='relu'))
model.add(Dense(units=num_classes, kernel_initializer='normal',activation='softmax'))
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
return model
model = create_model()
model.fit(x_train,y_train,epochs=10,batch_size=200)
score = model.evaluate(x_validation,y_validation)
print('MLP %.2f%%' % (score[1] * 100))
Epoch 1/10
60000/60000 [==============================] - 2s 39us/step - loss: 0.2161 - acc: 0.9346
Epoch 2/10
60000/60000 [==============================] - 2s 35us/step - loss: 0.0745 - acc: 0.9774
Epoch 3/10
60000/60000 [==============================] - 2s 35us/step - loss: 0.0452 - acc: 0.9852
Epoch 4/10
60000/60000 [==============================] - 2s 35us/step - loss: 0.0297 - acc: 0.9904
Epoch 5/10
60000/60000 [==============================] - 2s 36us/step - loss: 0.0245 - acc: 0.9921
Epoch 6/10
60000/60000 [==============================] - 2s 36us/step - loss: 0.0198 - acc: 0.9939
Epoch 7/10
60000/60000 [==============================] - 2s 36us/step - loss: 0.0153 - acc: 0.9949
Epoch 8/10
60000/60000 [==============================] - 2s 35us/step - loss: 0.0145 - acc: 0.9952
Epoch 9/10
60000/60000 [==============================] - 2s 35us/step - loss: 0.0157 - acc: 0.9949
Epoch 10/10
60000/60000 [==============================] - 2s 35us/step - loss: 0.0085 - acc: 0.9974
10000/10000 [==============================] - 0s 46us/step
MLP 98.23%