基于tensorflow.js的在线手写多数字识别代码
时间: 2023-05-26 18:01:40 浏览: 151
A:以下是基于tensorflow.js的在线手写多数字识别代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.3.0/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mnist@3.2.1/dist/mnist.js"
></script>
</head>
<body>
<canvas id="canvas" width="280" height="280"></canvas>
<button id="predict" onclick="predict()">Predict</button>
<div id="result"></div>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var mousePressed = false;
var lastX, lastY;
var offsetLeft = canvas.parentElement.offsetLeft;
var offsetTop = canvas.parentElement.offsetTop;
canvas.addEventListener(
"mousedown",
function (e) {
mousePressed = true;
lastX = e.clientX - offsetLeft + window.pageXOffset;
lastY = e.clientY - offsetTop + window.pageYOffset;
},
false
);
canvas.addEventListener(
"mousemove",
function (e) {
if (mousePressed) {
mouseX = e.clientX - offsetLeft + window.pageXOffset;
mouseY = e.clientY - offsetTop + window.pageYOffset;
draw(lastX, lastY, mouseX, mouseY);
lastX = mouseX;
lastY = mouseY;
}
},
false
);
canvas.addEventListener(
"mouseup",
function (e) {
mousePressed = false;
},
false
);
canvas.addEventListener(
"mouseleave",
function (e) {
mousePressed = false;
},
false
);
function draw(lx, ly, mx, my) {
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.lineWidth = 15;
ctx.lineJoin = "round";
ctx.moveTo(lx, ly);
ctx.lineTo(mx, my);
ctx.closePath();
ctx.stroke();
}
async function predict() {
const model = await tf.loadLayersModel(
"https://storage.googleapis.com/tfjs-models/tfjs/mnist_v1/model.json"
);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const x = tf.browser.fromPixels(imageData, 1).reshape([1, 28, 28, 1]);
const output = model.predict(x);
const prediction = Array.from(output.dataSync()).indexOf(
Math.max(...Array.from(output.dataSync()))
);
document.getElementById("result").textContent = `Prediction: ${prediction}`;
}
</script>
</body>
</html>
```
该代码使用MNIST数据集训练了一个深度卷积神经网络模型,并使用canvas API在浏览器中创建了一个可以手写数字的画布。当用户点击预测按钮时,模型将用于识别用户所绘制的数字,并将最可能的数字打印在页面上。
阅读全文