In [2]:
#%env KERAS_BACKEND=theano # This is WRONG, use K.set_image_dim_ordering('th') instead
#import numpy
#import theano
#print numpy.__version__
#print theano.__version__
#import keras
#print keras.__version__
import numpy as np
np.random.seed(123) # for reproducibility
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
#from keras import backend as K
#K.set_image_dim_ordering('th')
%matplotlib inline
In [2]:
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
In [3]:
print X_train.shape
print y_train
print X_test.shape
print y_test
In [4]:
from matplotlib import pyplot as plt
plt.imshow(X_train[2], cmap='gray')
Out[4]:
In [5]:
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1 )
print X_train.shape
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
In [6]:
# Convert 1-dimensional class arrays to 10-dimensional class matrices
Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)
In [3]:
model = Sequential()
model.add(Convolution2D(32, 3, 3, activation='relu', input_shape=(28,28,1)))
model.add(Convolution2D(32, 3, 3, activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
model.summary()
In [5]:
model.layers[0].get_config()
Out[5]:
In [8]:
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
In [9]:
history=model.fit(X_train, Y_train, validation_split=0.2,
batch_size=400, nb_epoch=20, verbose=1)
In [10]:
score = model.evaluate(X_test, Y_test, verbose=1)
In [11]:
print("%s: %.2f%%" % (model.metrics_names[1], score[1]*100))
In [24]:
# calculate predictions
predictions = model.predict(X_test)
# round predictions
rounded = [[round(r) for r in x] for x in predictions]
print(predictions)
In [25]:
print (Y_test)
rm=np.array(rounded)
print (rm)
rm.shape
np.subtract(Y_test, rm)
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(Y_test, rm)
print (mse)
In [12]:
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
In [27]:
from keras.utils.visualize_util import plot
plot(model)
In [ ]: