<html>
<body id='body'>
<button onclick="StartData(event)"> Start</button>
<button onclick="getStopCordinates(event)">Stop</button>
<script>
let inputs = [];
let labels = [];
function Mouse(event) {
inputs.push({ x: event.clientX, y: event.clientY })
}
function StartData() {
document.getElementById('body').addEventListener("mouseover", Mouse())
}
function getStopCordinates(event) {
labels.push({ x: event.clientX, y: event.clientY })
document.getElementById('body').removeEventListener("mouseover", Mouse())
}
</script>
</body>
</html>
我正在使用上面的代码来捕获鼠标在体内的所有x y坐标。当用户将指针移向停止按钮时,我正在为此捕获所有x,y坐标。当用户单击停止时,我也在捕获停止坐标。现在我想从捕获的点训练tensorflow js模型,以便当用户以相同的轨迹移动鼠标时,我可以预测他将单击停止按钮。
tensorflow代码:
const model = tf.sequential();
// Add a single hidden layer
model.add(tf.layers.dense({inputShape: [2], units: 1, useBias: true}));
// Add an output layer
model.add(tf.layers.dense({units: 1, useBias: true}));
const inputTensor = tf.tensor2d(inputs, [inputs.length, 1]);
const labelTensor = tf.tensor2d(labels, [labels.length, 1]);
trainModel(model,inputs,labels)
async function trainModel(model, inputs, labels) {
// Prepare the model for training.
model.compile({
optimizer: tf.train.adam(),
loss: tf.losses.meanSquaredError,
metrics: ['mse'],
});
const batchSize = 32;
const epochs = 50;
return await model.fit(inputs, labels, {
batchSize,
epochs,
shuffle: true,
callbacks: tfvis.show.fitCallbacks(
{ name: 'Training Performance' },
['loss', 'mse'],
{ height: 200, callbacks: ['onEpochEnd'] }
)
});
}
但是由于输入和标签不相同,此代码会产生错误,因此如何针对上述结果更正此代码?
答案 0 :(得分:0)
输入和标签应该是数组数组,而不是对象数组。输入应该是
[[1, 2], [4, 6], ...]
标签也一样。
由于您要预测2个值,因此最后一层的单位数应为2
const model = tf.sequential();
// Add a single hidden layer
model.add(tf.layers.dense({inputShape: [2], units: 1, useBias: true}));
// Add an output layer
model.add(tf.layers.dense({units: 1, useBias: true}));
最后一件事-当然不是最不重要的-是添加激活以便为模型添加非线性