0

More than 5 years have passed since last update.

Posted at

# 概要

jsdoでtensorflow.jsやってみた。

# サンプルコード

``````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();
}
const tx = [];
const 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);

var w1 = [0.6203325, -1.027319, 1.8841791, -3.2817535, 1.2214272, 0.9679314, 1.4196726, 7.171823, 1.3714954, 3.7268815, 0.0598045, 1.1944624];
var b1 = [1.1656082, -2.0180476, -6.9387307, 3.3653135, -1.7032033, -2.8969588, 0.0565524, -9.5316219, -5.7146306, -2.8060255, -0.3085915, -6.3642092];
var w2 = [-1.2655445, -1.0401167, 0.2071615, -0.4695872, -2.6633599, -0.5835096, 1.2490041, 1.2825323, -1.5088843, 0.6767025, 0.0224434, 1.6849496];
var b2 = -0.2928229;
function tanh(x) {
if (x > 20) return 1;
else if (x < -20) return -1;
else
{
var a = Math.exp(x);
var b = Math.exp(-x);
return (a - b) / (a + b);
}
}

var i;
var j;
var y = [];
for (i = 0; i < 20; i++)
{
var x = i / 3.0;
var sum = 0;
var d = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (j = 0; j < 12; j++)
{
d[j] += w1[j] * x + b1[j];
}
for (j = 0; j < 12; j++)
{
d[j] = tanh(d[j]);
}
for (j = 0; j < 12; j++)
{
sum += w2[j] * d[j];
}
sum += b2;
sum = tanh(sum);
y.push(sum);
}
draw(y, 1);

``````

# 成果物

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