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.

#概要

plunkerでtensorflow.jsやってみた。
callbacks使ってみた。

#サンプルコード




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

const model = tf.sequential();
model.add(tf.layers.dense({
	units: 40,
	activation: 'tanh',
	inputShape: [1]
}));
model.add(tf.layers.dense({
	units: 1,
	activation: 'tanh'
}));
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();
c = [];
model.fit(xs, ys, {
	batchSize: 200,
	epochs: 2000,
 	callbacks: {
		onEpochEnd: (epoch, logs) => {
			if (epoch % 10 == 0) 
			{
			  c.push(logs.loss);
			  draw(c, 1);
			}
		},
	}
}).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, 2);
});


#成果物

以上。

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?