神经网络:手写数字图像识别

本文介绍了如何使用Python和Keras库加载MNIST数据集,构建一个包含Flatten、ReLU和Softmax层的神经网络模型,编译模型后进行10轮训练,评估测试性能,并成功预测了测试集中的图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、导入相关库函数

import matplotlib.pyplot as plt
import tensorflow as tf
import keras
import numpy as np

二、载入mnist数据集 

使用keras.中的mnist数据集

(train_images, train_labels), (test_images, test_labels)=\
keras.datasets.mnist.load_data()

三、测试数据的情况,数据集图像和label标签

x = train_images[2]
y = train_labels[2]
plt.title('label: %i' % y)
plt.imshow(x, cmap=plt.cm.gray_r, interpolation='nearest')

四、建立神经网络模型

keras中有API帮助建立,用Sequential的AIP建立

model = keras.Sequential([
    #模型是多层的,底层是输入层,做Flatten,input_shape分辨率28*28
    keras.layers.Flatten(input_shape=(28,28)),
    #隐藏层,使用relu
    keras.layers.Dense(128, activation=tf.nn.relu),
    #输出层,10分类,数字从0~9,一共10种(选择softmax)
    keras.layers.Dense(10,activation=tf.nn.softmax)
])

五、将模型进行compile,优化器optimizers.Adam(),选择损失函数loss,用精度来度量

model.compile(optimizer=tf.optimizers.Adam(),
             loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

六、打印model,神经网络模型,三层结构

看一下神经网络模型结构:三层,输入层784,隐藏层128,输出层10

model.summary()

七、训练神经网络模型,精度在增长,loss减少 

epochs迭代次数,这里选择10次迭代

model.fit(train_images,train_labels,epochs=10)

八、评估,测试模型性能

test_loss,test_acc = model.evaluate(test_images, test_labels)

九、训练的模型进行预测

predictions = model.predict(test_images)

十、测试模型,用测试集进行

预测结果为

[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.],1的index为2,预测值为2,和真实值一致,预测成功。
x_test = test_images[888]
y_test = test_labels[888]
y_pred = predictions[888]

#打印x_test图像
plt.imshow(x_test,cmap=plt.cm.gray_r,interpolation='nearest')

y_pred2 = np.around(
    y_pred,
    decimals=1
)
print(y_pred2)
output:

[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]

十一、完整代码 

import matplotlib.pyplot as plt
import tensorflow as tf
import keras
import numpy as np

#载入mnist数据集
(train_images, train_labels), (test_images, test_labels)=\
keras.datasets.mnist.load_data()

#建立神经网络模型
#keras中有API帮助建立,用Sequential的AIP建立
model = keras.Sequential([
    #模型是多层的,底层是输入层,做Flatten,input_shape分辨率28*28
    keras.layers.Flatten(input_shape=(28,28)),
    #隐藏层,使用relu
    keras.layers.Dense(128, activation=tf.nn.relu),
    #输出层,10分类,数字从0~9,一共10种(选择softmax)
    keras.layers.Dense(10,activation=tf.nn.softmax)
])

#将模型进行compile,优化器optimizers.Adam(),选择损失函数loss,用精度来度量
model.compile(optimizer=tf.optimizers.Adam(),
             loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

#训练神经网络模型,精度在增长,loss减少
#epochs迭代次数,这里选择10次迭代
model.fit(train_images,train_labels,epochs=10)

#评估,测试模型性能
#在测试数据集上进行评估
test_loss,test_acc = model.evaluate(test_images, test_labels)

#刚刚训练的模型进行预测
predictions = model.predict(test_images)

x_test = test_images[888]
y_test = test_labels[888]
y_pred = predictions[888]

#打印x_test图像
plt.imshow(x_test,cmap=plt.cm.gray_r,interpolation='nearest')

y_pred2 = np.around(
    y_pred,
    decimals=1
)
print(y_pred2)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程初学者01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值