# Here is posted a basic program of running KERAS to develop a neural network to classify handwritten digits (MNIST dataset)
"""
KERAS for Digits Classification
@author: YL
"""
#Initialization
from keras.models import Sequential
from keras.layers import Dense
import os
wdir = '....certain path desired....'
os.chdir(wdir)
#data loading
wdir = '....certain path desired....'
os.chdir(wdir)
import mnist_loader
data = mnist_loader.load_data()
data_train = data[0] # tube structure containing X and Y
data_test = data[2] # same structure as the training data
#Convert 1-D label to a matrix of labels of the same dimension of the desired output, that is, 10 neurons in the output
from keras.utils.np_utils import to_categorical
X_train = data_train[0] #50000*784
Y_train = to_categorical(data_train[1],10) #50000*10, very important for objective or loss function
X_test = data_test[0] #10000*784
Y_test = to_categorical(data_test[1],10) #10000*10
#Create a 784-30-10 three-layer neural network
model = Sequential()
model.add(Dense(30, input_dim = 784, init = 'uniform', activation= 'sigmoid'))
model.add(Dense(10,activation = 'sigmoid'))
#Compile the model
from keras.optimizers import SGD
model.compile(loss='mean_squared_error', optimizer=SGD(lr=3.0, momentum=0.9, nesterov=True),metrics=['accuracy'])
#Fit the model
import numpy as np
model.fit(X_train, Y_train, nb_epoch=20, batch_size=10)
#Evaluate the model
loss_and_metrics = model.evaluate(X_test, Y_test)
#Results Display
print "%s: %.2f%%" %(model.metrics_names[1], loss_and_metrics[1]*100)
#test results
32/10000 [..............................] - ETA: 0s
1440/10000 [===>..........................] - ETA: 0s
2784/10000 [=======>......................] - ETA: 0s
4320/10000 [===========>..................] - ETA: 0s
5760/10000 [================>.............] - ETA: 0s
7136/10000 [====================>.........] - ETA: 0s
8608/10000 [========================>.....] - ETA: 0s>>> print "%s: %.2f%%" %(model.metrics_names[1], loss_and_metrics[1]*100)
acc: 94.52% (Accuracy)