你的本地机器上需要有一台运行中的服务器来托管权重文件。你可以在 GitHub 上创建一个 apache 服务器或者托管网页,就像我在我的项目中所做的那样(https://github.com/zaidalyafeai/zaidalyafeai.github.io/tree/master/sketcher)。
接着,通过下面的代码将模型加载到浏览器:
model = await tf.loadModel('model/model.json')
关键字 await 的意思是等待模型被浏览器加载。
预处理
在进行预测前,我们需要对数据进行预处理。首先从画布中获取图像数据:
//the minimum boudning box around the current drawing
const mbb = getMinBox
//cacluate the dpi of the current window
const dpi = window.devicePixelRatio
//extract the image data
const imgData = canvas.contextContainer.getImageData(mbb.min.x * dpi, mbb.min.y * dpi,
(mbb.max.x - mbb.min.x) * dpi, (mbb.max.y - mbb.min.y) * dpi);
文章稍后将介绍 getMinBox。dpi 变量被用于根据屏幕像素的密度对裁剪出的画布进行拉伸。
我们将画布当前的图像数据转化为一个张量,调整大小并进行归一化处理:
function preprocess(imgData)
{
return tf.tidy(=>{
//convert the image data to a tensor
let tensor = tf.fromPixels(imgData, numChannels= 1)
//resize to 28 x 28
const resized = tf.image.resizeBilinear(tensor, [28, 28]).toFloat
// Normalize the image
const offset = tf.scalar(255.0);
const normalized = tf.scalar(1.0).sub(resized.div(offset));
//We add a dimension to get a batch shape
const batched = normalized.expandDims(0)
return batched
})
}
我们使用 model.predict 进行预测,这将返回一个规模为「N, 100」的概率。
const pred = model.predict(preprocess(imgData)).dataSync
我们可以使用简单的函数找到 top 5 概率。
提升准确率
请记住,我们的模型接受的输入数据是规模为 [N, 28, 28, 1] 的张量。我们绘图画布的尺寸为 300*300,这可能是两个手绘图像的大小,或者用户可以在上面绘制一个小图像。最好只裁剪包含当前手绘图像的方框。为了做到这一点,我们通过找到左上方和右下方的点来提取围绕图像的最小边界框。
//record the current drawing coordinates
function recordCoor(event)
{
//get current mouse coordinate
var pointer = canvas.getPointer(event.e);
var posX = pointer.x;
var posY = pointer.y;
//record the point if withing the canvas and the mouse is pressed
if(posX >=0 && posY >= 0 && mousePressed)
{
coords.push(pointer)
}
}
//get the best bounding box by finding the top left and bottom right cornders
function getMinBox{
var coorX = coords.map(function(p) {return p.x});
var coorY = coords.map(function(p) {return p.y});
//find top left corner
var min_coords = {
x : Math.min.apply(, coorX),
y : Math.min.apply(, coorY)
}
//find right bottom corner
var max_coords = {
x : Math.max.apply(, coorX),
y : Math.max.apply(, coorY)
}
return {
min : min_coords,
max : max_coords
}
}
用手绘图像进行测试
下图显示了一些第一次绘制的图像以及准确率最高的类别。所有的手绘图像都是我用鼠标画的,用笔绘制的话应该会得到更高的准确率。
原文链接:https://medium.com/tensorflow/train-on-google-colab-and-run-on-the-browser-a-case-study-8a45f9b1474e
✄------------------------------------------------
加入机器之心(全职记者 / 实习生):[email protected]
投稿或寻求报道:content@jiqizhixin.com
广告 & 商务合作:[email protected]
閱讀更多 坤艮機器之心 的文章