0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TensorFlowのGradientDescentOptimizerでValueErrorに困った件

Posted at

TensorFlowの勉強をしている際にGradientDescentOptimizerのValueErrorで詰まったので、忘れないように解決方法(チェックすべきポイント)をメモに残しておく。

エラーが出たコード

import tensorflow as tf

x = tf.Variable(0, name = 'x')
func = (x - 1)**2

optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1)

train_step = optimizer.minimize(func)

# 以下はエラー原因には無関係
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(20):
        sess.run(train_step)
    print('x = ', sess.run(x))

実行結果は以下のようになり、どこが間違っているか延々と悩んだというお話。
ValueError: Invalid type tf.int32 for pow_3:0, expected: [tf.float32, tf.float64, tf.float16, tf.bfloat16].

エラー原因

GradientDescentOptimizerはFloatにしか対応していないため、***0(Int)ではなく0.(Float)***と記述しなくてはいけなかった。

x = tf.Variable(0., name = 'x')

上記以外、他の部分のコードは修正しなくてOK。
後になって考えればエラーメッセージを冷静に読めば分かったんだけど、TensorFlowのエラーメッセージに慣れていなかったことと、エラー箇所がtrain_stepの部分を示していて思考がそっちばかりにハマっていた…
(参考書にも注意ポイントとして明記しておいて欲しかった)

固定観念に囚われずに愚直に学びなさい、という教訓にはなったかな?

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?