I am trying to train a Tensor-flow js model on images coming in from my web cam. Basically I'm trying to recreate the pac-man tensor-flow game. The model isn't converging and is pretty much useless after training. I have a feeling its how I'm prepping the data.
Grabbing the image from the canvas
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]))
}
Train function
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
}
Model
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())
}
Predicting
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
}
The callback prints the losses but they do no converge to anything and the predictions are way off (random)
See Question&Answers more detail:
os