A Case Study of KERAS for Digits Classification

# 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)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值