0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

tensorflow.jsAdvent Calendar 2018

Day 8

tensorflow.jsでsin その2

Posted at

#概要
tensorflow.jsでsin問題やってみた。
modelを使わないで、やってみた。

#写真

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 < 20; i++) 
    {
        ctx.lineTo(i * 10, hc - data[i] * 30);
    }
	ctx.stroke();
}
tx = [];
ty = [];
for (var i = 0; i < 20; i++) 
{
    var x = i / 3.0;    
    var y = Math.sin(x);
    tx.push(x);
    ty.push(y);
}
draw(ty, 0);
const train_x = tf.tensor1d(tx);
const train_y = tf.tensor1d(ty);
const w = tf.variable(tf.randomNormal([20], 0, 1));
const b = tf.variable(tf.zeros([20]));
const optimizer = tf.train.sgd(0.1);
function loss(pred, ypred) {
  	const cost = pred.sub(ypred).square().mean();
  	return cost;
}
function func(x) {
  	return w.mul(x).add(b);
}
for (let i = 0; i < 200; i++) 
{
    optimizer.minimize(() => {
      	const loss_var = loss(func(train_x), train_y);
      	loss_var.print();
      	return loss_var;
    })
}
const preds = func(train_x).dataSync();
draw(preds, 1);



#成果物

以上。

0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?