0

More than 5 years have passed since last update.

Posted at

# 概要

tensorflow.jsでsin問題やってみた。

# サンプルコード

``````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 < 200; i++)
{
ctx.lineTo(i, hc - data[i] * 30);
}
ctx.stroke();
}
const model = tf.sequential();
units: 20,
activation: 'relu',
inputShape: [1]
}));
units: 20,
activation: 'relu'
}));
units: 1,
activation: 'linear'
}));
model.compile({
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();
model.fit(xs, ys, {
batchSize: 200,
epochs: 6000
}).then((d) => {
var str = "loss = ";
str += d.history.loss[0];
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, 1);
});

``````

# 成果物

Register as a new user and use Qiita more conveniently

1. You get articles that match your needs
2. You can efficiently read back useful information
3. You can use dark theme
What you can do with signing up
0