使用keras进行手写数字识别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import numpy as np
from tensorflow.keras.datasets import mnist
from tensorflow.python.keras.utils.np_utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD

#载入数据
(x_train,y_train),(x_test,y_test)=mnist.load_data()

print('x_shape',x_train.shape)#(60000,28,28)
print('y_shape:',y_train.shape)#(6000)

#(60000,28,28)-->(60000,784)
x_train=x_train.reshape(x_train.shape[0],-1)/255.0#除以255是做归一化,下同
x_test=x_test.reshape(x_test.shape[0],-1)/255.0

#换one hot格式(独热编码)
y_train=to_categorical(y_train,num_classes=10)
y_test=to_categorical(y_test,num_classes=10)

#创建模型,输入28*28=784个神经元,输出10个神经元
model=Sequential([
Dense(units=10,input_dim=784,bias_initializer='one',activation='softmax')
])
#定义优化器,训练过程中计算准确率
sgd=SGD(lr=0.2)
model.compile(
optimizer=sgd,
loss='mse',
metrics=['accuracy']
)

#训练模型
model.fit(x_train,y_train,batch_size=32,epochs=1)#epochs是训练周期

#评估模型
loss,accuracy=model.evaluate(x_test,y_test)
print('\ntest loss',loss)
print('accuracy',accuracy)

运行上述代码,得到如下结果:

1
2
test loss 0.021694928619265558
accuracy 0.8772

可以提高训练周期epochs来提高准确率

凡希 wechat
喜欢所以热爱,坚持干货分享,欢迎订阅我的微信公众号
呐,请我吃辣条