plunkerでtensorflow.js その28


概要

plunkerでtensorflow.jsやってみた。
関数フィッティングやってみた。

写真

サンプルコード


function predict(x) {
  return tf.tidy(() => {
    return tf.div(tf.exp(tf.mul(tf.mul(x.sub(a), x.sub(a)), tf.neg(b))), c)
  });
}
function loss(pred, label) {
  return tf.losses.meanSquaredError(pred, label).mean();
}
function train(xs, ys, numIterations) {
  for (let iter = 0; iter < numIterations; iter++) 
  {
    optimizer.minimize(() => {
      const pred = predict(xs);
      return loss(pred, ys);
    });
  }
}
const a = tf.variable(tf.scalar(Math.random() + 70));
const b = tf.variable(tf.scalar(Math.random()));
const c = tf.variable(tf.scalar(Math.random()));
const learningRate = 0.005;
const optimizer = tf.train.adamax(learningRate);
const numIterations = 300;
const yy =  [2, 0, 0, 0, 2, 0, 3, 0, 4, 4, 5, 0, 0, 2, 0, 0, 3, 0, 1, 0, 0, 2, 0, 1, 14, 16, 7, 8, 10, 10, 11, 17, 25, 12, 11, 19, 25, 14, 13, 15, 18, 19, 38, 29, 60, 41, 41, 9, 70, 58, 0, 62, 72, 66, 0, 39, 11, 35, 39, 44, 94, 27, 65, 114, 80, 81, 225, 173, 0, 87, 225, 317, 122, 522]
const xs = tf.tensor2d([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31], [32], [33], [34], [35], [36], [37], [38], [39], [40], [41], [42], [43], [44], [45], [46], [47], [48], [49], [50], [51], [52], [53], [54], [55], [56], [57], [58], [59], [60], [61], [62], [63], [64], [65], [66], [67], [68], [69], [70], [71], [72], [73], [74]], [74, 1]);
const ys = tf.tensor2d([[2], [0], [0], [0], [2], [0], [3], [0], [4], [4], [5], [0], [0], [2], [0], [0], [3], [0], [1], [0], [0], [2], [0], [1], [14], [16], [7], [8], [10], [10], [11], [17], [25], [12], [11], [19], [25], [14], [13], [15], [18], [19], [38], [29], [60], [41], [41], [9], [70], [58], [0], [62], [72], [66], [0], [39], [11], [35], [39], [44], [94], [27], [65], [114], [80], [81], [225], [173], [0], [87], [225], [317], [122], [522]], [74, 1]);
train(xs, ys, numIterations);
const aa = Number(a.dataSync());
const bb = Number(b.dataSync());
const cc = Number(c.dataSync());
//alert(aa + ", " + bb + ", " + cc);
var values = [];
for (var i = 0; i < 74; i++)
{
  values.push({
    x: i, 
    y: yy[i],
    pred: Math.exp((i - aa) * (i - aa) * - bb) / cc
  });
}
const spec = {
  '$schema': 'https://vega.github.io/schema/vega-lite/v2.json',
  'width': 300,
  'height': 300,
  'data': {
    'values': values
  },
  'layer': [{
    'mark': 'point',
    'encoding': {
      'x': {
        'field': 'x', 
        'type': 'quantitative'
      },
      'y': {
        'field': 'y', 
        'type': 'quantitative'
      }
    }
  }, {
    'mark': 'line',
    'encoding': {
      'x': {
        'field': 'x', 
        'type': 'quantitative'
      },
      'y': {
        'field': 'pred', 
        'type': 'quantitative'
      },
      'color': {
        'value': 'tomato'
      }
    }
  }]
};
vegaEmbed('#vis', spec);




成果物

以上。