2017-10-13 42 views
1

我正在學習使用tensorflow庫。每次我嘗試使用最簡單的(我猜)可能的基於漸變的學習示例時,我會得到相同的錯誤,這使得我陷入困境。最簡單的apply_gradients拋出'op'屬性錯誤

下面是代碼:

import tensorflow as tf 

x = tf.constant(1, dtype=tf.float32, name='X') 
a = tf.Variable(1, dtype=tf.float32, name= 'A') 
y = tf.constant(10, dtype=tf.float32, name='Y') 

ey = tf.multiply(x, a) 
los = (y - ey)**2 

optim = tf.train.GradientDescentOptimizer(learning_rate=0.2) 

sess = tf.Session() 
sess.run(tf.global_variables_initializer()) 
for counter in range(100): 
    grd = sess.run(optim.compute_gradients(loss=los)) 
    sess.run(optim.apply_gradients(grads_and_vars=grd)) 

就上線,我得到以下錯誤: AttributeError的: 'numpy.float32' 對象有沒有屬性 '運'。

預先感謝您的任何提示。

回答

0

apply_gradients的輸入必須是張量而不是numpy數組。因爲,它並不是要在學習的每一步被調用,而只是在構建圖形時調用一次。事實上,「創造」了「培訓的步驟」,其中變量是使用計算出的梯度

您應該使用那種代碼,而不是更新:

import tensorflow as tf 

x = tf.constant(1, dtype=tf.float32, name='X') 
a = tf.Variable(1, dtype=tf.float32, name= 'A') 
y = tf.constant(10, dtype=tf.float32, name='Y') 

ey = tf.multiply(x, a) 
los = (y - ey)**2 

optim = tf.train.GradientDescentOptimizer(learning_rate=0.2) 
grads, vars = zip(*optimizer.compute_gradients(loss)) 
train_step = optim.apply_gradients(grads_and_vars=grads) 

sess = tf.Session() 
sess.run(tf.global_variables_initializer()) 
for counter in range(100): 
    grd = sess.run(train_step, feed_dict = {...}) 
+0

哈......明白了。謝謝! – Broono

相關問題