COVID-19チャレンジ(フェーズ3)その3


概要

signateのCOVID-19チャレンジ(フェーズ3)やってみた。
tensorflow.jsでfitしてみた。

写真

サンプルコード


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() + 90));
const b = tf.variable(tf.scalar(Math.random() / 10));
const c = tf.variable(tf.scalar(Math.random() / 10));
const learningRate = 0.005;
const optimizer = tf.train.adamax(learningRate);
const numIterations = 300;
const yy =  [1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 3, 1, 6, 3, 3, 0, 0, 3, 2, 0, 0, 1, 0, 0, 2, 1, 4, 8, 12, 6, 7, 8, 10, 10, 15, 26, 12, 13, 11, 18, 25, 19, 9, 14, 18, 19, 36, 32, 56, 44, 33, 28, 59, 53, 56, 34, 63, 31, 17, 45, 41, 40, 54, 39, 47, 39, 71, 96, 94, 123, 201, 169, 94, 242, 267, 278, 354, 366, 360, 242, 360, 514, 573, 632, 719, 499, 294, 482, 548, 573, 555, 584, 374, 346, 391, 452, 436, 434, 368, 210, 172, 281, 223, 188, 266, 305, 201, 176, 121]
const buffer = tf.buffer([yy.length, 1]);
const buffer2 = tf.buffer([yy.length, 1]);
for (var i = 0; i < yy.length; i++) 
{
    var x = i; 
    var y = yy[i];
    buffer.set(x, i, 0);
    buffer2.set(y, i, 0);
}
const xs = buffer.toTensor();
const ys = buffer2.toTensor();
train(xs, ys, numIterations);
const aa = Number(a.dataSync());
const bb = Number(b.dataSync());
const cc = Number(c.dataSync());
var values = [];
var j = 0;
var out = document.getElementById('out');
for (var i = 0; i < 130; i++)
{
  if (i < yy.length)
  {
    j = i;
  }
  values.push({
    x: i, 
    y: yy[j],
    pred: Math.exp((i - aa) * (i - aa) * - bb) / cc
  });
  out.value += Math.floor(Math.exp((i - aa) * (i - aa) * - bb) / cc);
  out.value += ",";
}
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);

成果物

以上。