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 2019

Day 5

plunkerでtensorflow.js その17

Last updated at Posted at 2019-11-04

#概要

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/

以上。

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?