逻辑回归手写体识别learn显示图片显示准确率
时间: 2023-06-15 21:06:56 浏览: 60
逻辑回归是一种二分类算法,不能直接用于手写体识别。不过,可以将逻辑回归与神经网络结合起来,实现手写体识别。以下是一个简单的示例代码:
```
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 加载数据集
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 创建占位符
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]))
# 定义模型
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 定义损失函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
# 定义优化器
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# 初始化变量
init = tf.global_variables_initializer()
# 训练模型
with tf.Session() as sess:
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# 计算准确率
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
print("Test accuracy:", test_accuracy)
# 显示一张图片
import matplotlib.pyplot as plt
import numpy as np
img = mnist.test.images[0]
plt.imshow(np.reshape(img, [28, 28]), cmap='gray')
plt.show()
```
这段代码使用 TensorFlow 实现了逻辑回归与 softmax 回归结合的手写体识别模型,并且计算了测试集准确率。在训练完成后,可以使用 matplotlib 库显示一张手写数字图片。