0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

plunkerでtensorflow.js その17

概要

plunkerでtensorflow.jsやってみた。
lstm使ってみた。
sin波、学習させてみた。

サンプルコード


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 < 200; i++)
    {
        ctx.lineTo(i, hc - data[i] * 30);
    }
    ctx.stroke();
}

const model = tf.sequential();
model.add(tf.layers.lstm({ 
  units: 64,
  returnSequences: false,
  inputShape: [2, 1]
}));
model.add(tf.layers.dense({
  units: 1, 
  activation: "tanh"
}));
model.compile({
  optimizer: 'adam',
  loss: 'meanSquaredError'
});

const buf0 = [];
const buf1 = [];
b = [];
for (var i = 0; i < 200; i++)
{
    var x = i / 30.0;
    var y = Math.sin(x);
    b.push(y);
}
for (var i = 0; i < 197; i++)
{
    buf0.push([[b[i]], [b[i + 1]]]);
    buf1.push([b[i + 2]]);
}
draw(b, 0);

const xs = tf.tensor3d(buf0);
const ys = tf.tensor2d(buf1);
model.fit(xs, ys, {
    batchSize: 100,
    epochs: 100
}).then((d) => {
    var str = "loss = ";
    str += d.history.loss[0];
    alert(str);
    p = [];
    for (i = 0; i < 197; i++)
    {
        var x =  i / 30.0;
        var y0 = Math.sin(x);
        x =  (i + 1) / 30.0;
        var y1 = Math.sin(x);
        var pre = model.predict(tf.tensor3d([[[y0], [y1]]], [1, 2, 1]));
        var f = pre.dataSync();
        p.push(f);
    }
    draw(p, 1);
});


成果物

比較用

tanh
https://embed.plnkr.co/oVEtQXFPuAz2hLONXL4g/

以上。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
0
Help us understand the problem. What are the problem?