请写出手写数字识别代码,再设计一个前端,可以让用户进行识别操作
时间: 2023-06-19 13:10:38 浏览: 162
手写数字识别代码可以使用深度学习框架 TensorFlow 来实现。以下是一个简单的代码示例:
``` python
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 加载 MNIST 数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 创建输入变量 x 和输出变量 y_true
x = tf.placeholder(tf.float32, [None, 784])
y_true = tf.placeholder(tf.float32, [None, 10])
# 创建神经网络模型
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y_pred = tf.nn.softmax(tf.matmul(x, W) + b)
# 定义损失函数和优化器
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_true * tf.log(y_pred), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# 创建会话并训练模型
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_true: batch_ys})
# 测试模型准确率
correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y_true, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_true: mnist.test.labels}))
```
接着,可以使用 Flask 框架搭建一个简单的 Web 应用程序,让用户输入一张手写数字图片,然后进行识别操作。以下是一个简单的前端代码示例:
``` html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Handwritten Digit Recognition</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.4.0"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mnist@1.2.2"></script>
</head>
<body>
<canvas id="canvas" width="280" height="280" style="border: 1px solid black;"></canvas>
<br>
<button onclick="clearCanvas();">Clear</button>
<button onclick="predictDigit();">Predict</button>
<br>
<span id="result"></span>
<script>
var model;
async function loadModel() {
model = await tf.loadModel('model.json');
}
function clearCanvas() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillStyle = 'white';
context.fillRect(0, 0, 280, 280);
}
function getImageData() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageData = context.getImageData(0, 0, 280, 280);
var data = imageData.data;
var image = [];
for (var i = 0; i < data.length; i += 4) {
image.push(data[i] / 255);
}
return [image];
}
async function predictDigit() {
var image = getImageData();
var predictions = await model.predict(tf.tensor(image));
var digit = predictions.argMax(1).dataSync()[0];
var result = document.getElementById('result');
result.innerHTML = 'Predicted digit: ' + digit;
}
clearCanvas();
loadModel();
</script>
</body>
</html>
```
该前端代码使用 TensorFlow.js 和 MNIST 模型库来加载事先训练好的模型,并提供一个简单的绘图框,让用户输入手写数字图片。用户可以点击 Clear 按钮清除绘图框,或者点击 Predict 按钮进行识别操作。识别结果将显示在页面上。
阅读全文