手写数字识别
作者:互联网
#导入包
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
import tensorflow as tf
#载入数据
(x_train,y_train),(x_test,y_test) = tf.keras.datasets.mnist.load_data()
print(x_train.shape)
print(y_train.shape)
#x_train的数据shape为(60000,28,28)
#y_train的数据shape为(60000,)
#将x_train和x_test的shape转换成(60000,784)
#(60000,28,28)->(60000,784)
#由于其数值范围从0到255,因此除以255以实现归一化使得数据范围从0到1
x_train = x_train.reshape(x_train.shape[0],-1)/255.0
x_test = x_test.reshape(x_test.shape[0],-1)/255.0
print(x_train.shape)
#将y_train和t_test转换成one hot格式
y_train = keras.utils.to_categorical(y_train,num_classes=10)
y_test = keras.utils.to_categorical(y_test,num_classes=10)
(60000, 28, 28)
(60000,)
(60000, 784)
#创建模型,输入784个神经元,输出10个神经元
model = keras.Sequential()
model.add(keras.layers.Dense(10,input_dim=784))
model.add(keras.layers.Activation('softmax'))
sgd = keras.optimizers.SGD()
model.compile(optimizer=sgd,loss='mse',metrics=['accuracy'])
#开始训练模型
model.fit(x_train,y_train,batch_size=32,epochs=10)
Epoch 1/10
1875/1875 [] - 1s 364us/step - loss: 0.0897 - accuracy: 0.1654
Epoch 2/10
1875/1875 [] - 1s 365us/step - loss: 0.0778 - accuracy: 0.4778
Epoch 3/10
1875/1875 [] - 1s 362us/step - loss: 0.0647 - accuracy: 0.6280
Epoch 4/10
1875/1875 [] - 1s 366us/step - loss: 0.0544 - accuracy: 0.7044
Epoch 5/10
1875/1875 [] - 1s 363us/step - loss: 0.0474 - accuracy: 0.7379
Epoch 6/10
1875/1875 [] - 1s 362us/step - loss: 0.0419 - accuracy: 0.7721
Epoch 7/10
1875/1875 [] - 1s 361us/step - loss: 0.0384 - accuracy: 0.7947
Epoch 8/10
1875/1875 [] - 1s 360us/step - loss: 0.0354 - accuracy: 0.8128
Epoch 9/10
1875/1875 [] - 1s 359us/step - loss: 0.0329 - accuracy: 0.8291
Epoch 10/10
1875/1875 [] - 1s 358us/step - loss: 0.0310 - accuracy: 0.8394
<tensorflow.python.keras.callbacks.History at 0x2900506f208>
#评估模型
loss,accuracy = model.evaluate(x_test,y_test)
print('loss: ',loss)
print('accuracy: ',accuracy)
313/313 [==============================] - 0s 323us/step - loss: 0.0287 - accuracy: 0.8511
loss: 0.02871590293943882
accuracy: 0.8511000275611877
标签:loss,数字,10,train,step,1875,手写,识别,accuracy 来源: https://blog.csdn.net/lovekobe1997/article/details/114584379