Python :MNIST手写数据集识别 + 手写板程序 最详细,直接放心,大胆地抄!跑不通找我,我包教!
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 下载并加载MNIST数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 每个批次大小
batch_size = 64
# 计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
# 定义两个placeholder
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
# 创建一个简单的神经网络(仅含一个隐藏层)
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x, W) + b)
# 定义损失函数和优化器
loss_function = tf.reduce_mean(-tf.reduce_sum(y * tf.log(prediction), reduction_indices=1))
optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss_function)
# 初始化变量
init = tf.global_variables_initializer()
# 结果存储
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 开启会话
with tf.Session() as sess:
sess.run(init)
# 训练模型
for epoch in range(21): # 训练21轮
for batch in range(n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
# 每轮训练后测试模型
acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
print("Iter " + str(epoch) + ", Testing Accuracy= " + str(acc))
# 手写板程序
def do_something_with_image(img):
# 对图像数据进行处理,例如转换为28x28的二维数组
img = img.reshape(28, 28)
# 可视化图像
plt.imshow(img, cmap='Greys')
plt.show()
# 预测图像
prediction_value = sess.run(prediction, feed_dict={x: [img]})
print("The model thinks the image is: ", np.argmax(prediction_value))
# 读取一张图像作为例子
image_to_recognize = np.zeros([784])
# 假设这里从某个来源获取了一个28x28的图像数组,并将其转换为一维数组
# image_array = ...
# image_to_recognize = image_array.reshape(784)
# 调用函数处理图像
do_something_with_image(image_to_recognize)
这段代码首先加载了MNIST数据集,然后定义了一个简单的神经网络(仅含一个隐藏层)
评论已关闭