LoginSignup
0
0

More than 5 years have passed since last update.

勾配降下法の練習の為によくある頭の体操を解いてみる

Posted at

よくSNSでシェアされるIQを図る系の問題

1 +  5 = 18
2 +  7 = 27
3 +  9 = 36
5 + 10 = 45

4 + 20 = ??

という頭の体操(?)をjsで勾配降下法で解いてみる。

const inputLayer = [
  [1, 5],
  [2, 7],
  [3, 9],
  [5, 10],
];

const labels = [
  18,
  27,
  36,
  45,
];

教師データと正解ラベル

let bias = [0, 0, 0, 0,];
const output = (w, x) => w[0] * (x[0] + x[1]) + w[1] * x[0] + w[2] * x[1] + w[3];

適当に作った評価式

function targetFunction(bias) {
  let error = 0;
  for (let i = 0;i < inputLayer.length;i++) {
    let input = inputLayer[i];
    let b = output(bias, input);
    error += Math.pow(labels[i] - b, 2);
  }
  return error;
}

errorが0に近ずくように学習していく

const n0 = bias.length;
for (let i = 0;i < 100;i++) {
  for (let j = 0;j < n0;j++) {
    let old = bias[j];
    let before = targetFunction(bias);
    bias[j] = old + 0.001;
    let after = targetFunction(bias);
    bias[j] = old + (before - after) * 1;
  }
  if (targetFunction(bias) < 0.0001) {
    break;
  }
  console.log(i, targetFunction(bias));
}

実行した結果

99 0.0004953073198085481
[ 2.9489024031645927,
  0.03969341058294724,
  0.054454721873473506,
  0.0034584048363291682 ]
4 + 20 =  72.02498416058782

100回ぐらい回せば収束した
どうも二つの数字を足したものに3辺りを掛けたものが答えらしい。
本当の正解は知りません。

ソースコード

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