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

Posted ldragon2000

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于tensorflow的手写数字识别代码相关的知识,希望对你有一定的参考价值。

基于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的手写数字识别代码的主要内容,如果未能解决你的问题,请参考以下文章

Tensorflow暑期实践——基于单个神经元的手写数字识别(全部代码)

AI常用框架和工具丨10. TensorFlow实现基于LeNet5的手写数字识别

AI常用框架和工具丨10. TensorFlow实现基于LeNet5的手写数字识别

深度学习--TensorFlow(项目)识别自己的手写数字(基于CNN卷积神经网络)

AI常用框架和工具丨11. 基于TensorFlow(Keras)+Flask部署MNIST手写数字识别至本地web

AI常用框架和工具丨11. 基于TensorFlow(Keras)+Flask部署MNIST手写数字识别至本地web