Created
November 26, 2018 13:16
-
-
Save jutikorn/c5468d3c87de6933c61ea011c62e264e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
from keras.datasets import mnist | |
import matplotlib.pyplot as plt | |
import keras | |
# input image dimensions | |
def plot_image(xTest,YRealValue,YPredic): | |
plt.figure(3) | |
fig, axes = plt.subplots(10, 10, figsize=(28, 28)) | |
test_images = xTest.reshape(-1, 28, 28) | |
for i, ax in enumerate(axes.flat): | |
ax.imshow(test_images[i*10+i],cmap=plt.get_cmap('gray')) | |
# ax.text(0.05, 0.05, str(YPredic[i*10+i]), | |
# transform=ax.transAxes, | |
# color='green' if (YRealValue[i*10+i][0] == YPredic[i*10+i]) else 'red') | |
img_rows, img_cols = 28, 28 | |
(x_train, y_train), (x_test, y_test) = mnist.load_data() | |
print(x_train.shape) | |
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')) | |
# show the plot | |
plt.show() | |
x_train = x_train.reshape(60000, 784) | |
x_test = x_test.reshape(10000, 784) | |
x_train = x_train.astype('float32') | |
x_test = x_test.astype('float32') | |
x_train /= 255 | |
x_test /= 255 | |
print(x_train.shape[0], 'train samples') | |
print(x_test.shape[0], 'test samples') | |
print("Y train sample = ",y_train[0]) | |
# convert class vectors to binary class matrices | |
y_train = keras.utils.to_categorical(y_train, 10) | |
y_test = keras.utils.to_categorical(y_test, 10) | |
print("Y train sample with one-hot = ",y_train[0]) | |
from keras.models import Sequential | |
from keras.layers import Dense | |
from keras.layers import Dropout | |
model = Sequential() | |
model.add(Dense(512, activation='sigmoid', input_shape=(784,))) | |
model.add(Dropout(0.2)) | |
model.add(Dense(512, activation='sigmoid')) | |
model.add(Dropout(0.2)) | |
model.add(Dense(10, activation='softmax')) | |
model.summary() | |
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) | |
model.fit(x_train,y_train,batch_size=100,epochs=1000,validation_data=(x_test,y_test)) | |
score = model.evaluate(x_test, y_test, verbose=0) | |
print('Test loss:', score[0]) | |
print('Test accuracy:', score[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment