【发布时间】:2019-09-20 10:44:08
【问题描述】:
我正在尝试在来自我的网络摄像头的图像上训练一个张量流 js 模型。基本上我正在尝试重新创建 pac-man 张量流游戏。该模型没有收敛,并且在训练后几乎没用。我有一种感觉,我是如何准备数据的。
从画布中抓取图像
function takePhoto(label) {
let canv = document.getElementById("canv")
let cont = canv.getContext("2d")
cont.drawImage(video, 0, 0, width, height)
let data = tf.browser.fromPixels(canv, 3)
data.toFloat().div(tf.scalar(127)).sub(tf.scalar(1))
return data
}
function addExample(label){
let data = takePhoto()
addData(train_data => train_data.concat(data))
addLabel(train_labels => train_labels.concat(labels[label]))
}
训练功能
export async function train_model(image,label){
let d = tf.stack(image)
let l = tf.oneHot(tf.tensor1d(label).toInt(),4)
let data = await model.fit(d,l,{epochs:10,batchSize:label[0].length,callbacks:{
onBatchEnd: async (batch, logs) =>{
console.log(logs.loss.toFixed(5))
}
}})
return data
}
型号
export function buildModel(){
model = tf.sequential({layers:[
tf.layers.conv2d({inputShape:[width,height,3],
kernelSize:3,
filters:5,
activation :"relu"}),
tf.layers.flatten(),
tf.layers.dense({units:128, activation:"relu",useBias:true}),
tf.layers.dense({units:32, activation:"relu"}),
tf.layers.dense({units:4, activation:"softmax"})
]})
model.compile({metrics:["accuracy"], loss:"categoricalCrossentropy", optimizer:"adam",learningRate:.00001})
console.log(model.summary())
}
预测
export async function predict(img){
let pred = await tf.tidy(() => {
img = img.reshape([1,width,height, 3]);
const output = model.predict(img);
let predictions = Array.from(output.dataSync());
return predictions
})
return pred
}
回调会打印损失,但它们不会收敛到任何东西,并且预测会偏离(随机)
【问题讨论】:
标签: tensorflow image-processing data-processing tensorflow.js