LoginSignup
6

More than 5 years have passed since last update.

posted at

updated at

Organization

わざわざTensorFlowの機械学習で$\sqrt{2}$を計算する

わざわざ機械学習で計算してみる。もちろんtf.pow(2., 0.5)でできるが、powを使わずにする。

概要

$\sqrt{2}$は$x^2-2=0$の解で正のものだから、$x^2-2$の絶対値が最小になるところを探す。($-\sqrt{2}$になる可能性が残るが、気にしないことにする。)

しかし、絶対値の関数$|x|$は肝心の$x=0$で微分ができないので、$(x^2-2)^2$を損失関数として利用する。TensorFlowといえど、数式の選択などはきちんと考えないといけないようです。

あとは、適当にOptimizerを用意して、学習させる。

詳細

次のようにする。

# coding: utf-8
import tensorflow as tf
import math
ans = math.sqrt(2.) # 結果との比較用

x = tf.Variable(1.)
loss = (x*x-2)*(x*x-2)
# loss = tf.abs(x*x-2) # これは上手くいかない
opt = tf.train.GradientDescentOptimizer(0.1)
train = opt.minimize(loss)

init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    for i in xrange(100):
        sess.run(train)
        result = sess.run(x)
        print result, result - ans

機械学習では、勾配を計算しその方向へ変数の値を更新するが、上のコードでわかるように、自力で微分をすることなく済んでいる。optが自動で微分してくれている。

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
What you can do with signing up
6