#概要
plunkerでtensorflow.jsやってみた。
callbacks使ってみた。
#サンプルコード
tf.setBackend('cpu');
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function draw(data, n) {
var hc = n * 100 + 100;
ctx.strokeStyle = "#f00";
ctx.lineWidth = 1;
ctx.moveTo(0, hc);
for (var i = 1; i < data.length; i++)
{
ctx.lineTo(i, hc - data[i] * 30);
}
ctx.stroke();
}
const model = tf.sequential();
model.add(tf.layers.dense({
units: 40,
activation: 'tanh',
inputShape: [1]
}));
model.add(tf.layers.dense({
units: 1,
activation: 'tanh'
}));
model.compile({
optimizer: 'adam',
loss: 'meanSquaredError'
});
const buffer = tf.buffer([200, 1]);
const buffer2 = tf.buffer([200, 1]);
b = [];
for (var i = 0; i < 200; i++)
{
var x = i / 30.0;
var y = Math.sin(x);
b.push(y);
buffer.set(x, i, 0);
buffer2.set(y, i, 0);
}
draw(b, 0);
const xs = buffer.toTensor();
const ys = buffer2.toTensor();
c = [];
model.fit(xs, ys, {
batchSize: 200,
epochs: 2000,
callbacks: {
onEpochEnd: (epoch, logs) => {
if (epoch % 10 == 0)
{
c.push(logs.loss);
draw(c, 1);
}
},
}
}).then((d) => {
var str = "loss = ";
str += d.history.loss[0];
alert(str);
p = [];
for (i = 0; i < 200; i++)
{
var x = i / 30.0;
var pre = model.predict(tf.tensor2d([[x]], [1, 1]));
var f = pre.dataSync();
p.push(f);
}
draw(p, 2);
});
#成果物
以上。