Help us understand the problem. What is going on with this article?

tensorflow.jsでsin

More than 1 year has passed since last update.

概要

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

以上。

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした