概要

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

写真

image.png

サンプルコード

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();
model.add(tf.layers.dense({
    units: 20,
    activation: 'relu',
    inputShape: [1]
}));
model.add(tf.layers.dense({
    units: 20,
    activation: 'relu'
}));
model.add(tf.layers.dense({
    units: 1,
    activation: 'linear'
}));
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();
//alert(xs);
//alert(ys);
model.fit(xs, ys, {
    batchSize: 200, 
    epochs: 6000
}).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, 1);
});




成果物

http://jsdo.it/ohisama1/2DaC

以上。

Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.