码迷,mamicode.com
首页 > 其他好文 > 详细

基于tensorflow的手写数字识别代码

时间:2020-12-16 11:52:08      阅读:4      评论:0      收藏:0      [点我收藏+]

标签:poc   神经网络   util   max   mpi   ast   数据   metrics   mode   

基于tensorflow的手写数字识别代码

from keras.utils import to_categorical
from keras import models, layers, regularizers
from keras.optimizers import RMSprop
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()


train_images = train_images.reshape((60000, 28 * 28)).astype("float")
test_images = test_images.reshape((10000, 28 *28)).astype("float")
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

network = models.Sequential()
network.add(layers.Dense(units=128, activation=‘relu‘, input_shape=(28*28,),
                         kernel_regularizer=regularizers.l1(0.0001)))

# 百分之1使得神经元丧失性能
network.add(layers.Dropout(0.001))
network.add(layers.Dense(units=32, activation=‘relu‘, kernel_regularizer=regularizers.l1(0.0001)))
network.add(layers.Dropout(0.001))
network.add(layers.Dense(units=10, activation=‘softmax‘))


# 查看当前神经网络结构
print(network.summary())

# 编译步骤
network.compile(optimizer=RMSprop(lr=0.001), loss=‘categorical_crossentropy‘, metrics=[‘accuracy‘])

# 训练网络,使用fit 函数,epochs 表示训练多少回合,batch_size表示每次训练给多大的数据。
network.fit(train_images, train_labels, epochs=20, batch_size=128, verbose=2)

# 使用测试集来测试性能
y_pre = network.predict(test_images[:5])
print(y_pre, test_labels[:5])
test_loss, text_accuracy = network.evaluate(test_images,test_labels)
print("test_loss",test_loss,".  ","test_accuracy: ", text_accuracy)

运行结果如下:
技术图片

从结果可以看出,有一定程度的过拟合,优化代码可以解决

基于tensorflow的手写数字识别代码

标签:poc   神经网络   util   max   mpi   ast   数据   metrics   mode   

原文地址:https://www.cnblogs.com/ldragon2000/p/14117289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!