tape.gradient()以下梯度下降失敗,因為當回圈第二次運行時,回傳的梯度是無的。
w = tf.Variable(tf.random.normal((3, 2)), name='w')
b = tf.Variable(tf.zeros(2, dtype=tf.float32), name='b')
x = tf.constant([[1., 2., 3.]])
for i in range(10):
print("iter {}".format(i))
with tf.GradientTape() as tape:
#forward prop
y = x @ w b
loss = tf.reduce_mean(y**2)
print("loss is \n{}".format(loss))
print("output- y is \n{}".format(y))
#vars getting dropped after couple of iterations
print(tape.watched_variables())
#get the gradients to minimize the loss
dl_dw, dl_db = tape.gradient(loss,[w,b])
#descend the gradients
w = w.assign_sub(0.001*dl_dw)
b = b.assign_sub(0.001*dl_db)
iter 0
loss is
23.328645706176758
output- y is
[[ 6.8125362 -0.49663293]]
(<tf.Variable 'w:0' shape=(3, 2) dtype=float32, numpy=
array([[-1.3461215 , 0.43708783],
[ 1.5931423 , 0.31951016],
[ 1.6574576 , -0.52424705]], dtype=float32)>, <tf.Variable 'b:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>)
iter 1
loss is
22.634033203125
output- y is
[[ 6.7103477 -0.48918355]]
()
TypeError Traceback (most recent call last)
c:\projects\pyspace\mltest\test.ipynb Cell 7' in <cell line: 1>()
11 dl_dw, dl_db = tape.gradient(loss,[w,b])
13 #descend the gradients
---> 14 w = w.assign_sub(0.001*dl_dw)
15 b = b.assign_sub(0.001*dl_db)
TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'
我檢查了解釋漸變變為 的可能性的檔案None,但它們都沒有幫助。
uj5u.com熱心網友回復:
這是因為assign_sub回傳一個Tensor. 因此,在該行中,您將使用具有新值的張量w = w.assign_sub(0.001*dl_dw)覆寫。w因此,在下一步中,它Variable不再是 a,并且默認情況下不會被漸變磁帶跟蹤。這導致梯度變為None(張量也沒有該assign_sub方法,因此也會崩潰)。
相反,只需w.assign_sub(0.001*dl_dw)為b. 分配功能就地作業,因此不需要分配。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/450129.html
