LoginSignup
0

More than 5 years have passed since last update.

jsdoでtensorflow.js その6

Posted at

概要

jsdoでtensorflow.jsやってみた。
ウェイトとバイアスを注入してみた。

写真

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();
}
const buffer = tf.buffer([20, 1]);
const buffer2 = tf.buffer([20, 1]);
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);
    buffer.set(x, i, 0);
    buffer2.set(y, i, 0);
}
draw(ty, 0);
const train_x = buffer.toTensor();
const train_y = buffer2.toTensor();
var arr0 = [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 arr1 = [[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 arr2 = [-0.2928229];
var arr3 = [[-1.2655445], [-1.0401167], [0.2071615], [-0.4695872], [-2.6633599], [-0.5835096], [1.2490041], [1.2825323], [-1.5088843], [0.6767025], [0.0224434], [1.6849496]];
const w1 = tf.variable(tf.tensor(arr1));
const b1 = tf.variable(tf.tensor(arr0));
const w2 = tf.variable(tf.tensor(arr3));
const b2 = tf.variable(tf.tensor(arr2));
function func(x) {
    const h = tf.tanh(x.matMul(w1).add(b1));
    return tf.tanh(h.matMul(w2).add(b2));
}
const preds = func(train_x).dataSync();
draw(preds, 1);
var out1 = document.getElementById('src');
out1.value += b1 + '\n';
out1.value += w1 + '\n';
out1.value += b2 + '\n';
out1.value += w2 + '\n';



成果物

以上。

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