WARNING:tensorflow:The dtype of the target tensor must be floating (e.g. tf.float32) when calling GradientTape.gradient, got tf.int32
报错代码如下:
x = tf.random.normal([1,3])
b = tf.ones([1])
w = tf.ones([3,1])
y = tf.constant([1])
with tf.GradientTape() as tape:
tape.watch([w,b])
prob = tf.sigmoid(x @ w + b)
loss = tf.reduce_mean(tf.losses.MSE(prob,y))
grads = tape.gradient(loss,[w,b])
grads[0]
报错意思是目标张量必须要是浮点类型,但得到的是int32型。 我们知道MSE的计算中存在平方,所以x_val和x_pred的顺序是没有关系的,但是tf.reduce_mean(tf.losses.MSE())要求第二位必须是tf.float32型,所有我们可以这样改:
x = tf.random.normal([1,3])
b = tf.ones([1])
w = tf.ones([3,1])
#将y改为tf.float32型即可
y = tf.constant([1.])
with tf.GradientTape() as tape:
tape.watch([w,b])
prob = tf.sigmoid(x @ w + b)
loss = tf.reduce_mean(tf.losses.MSE(prob,y))
grads = tape.gradient(loss,[w,b])
grads[0]
或者
x = tf.random.normal([1,3])
b = tf.ones([1])
w = tf.ones([3,1])
y = tf.constant([1])
with tf.GradientTape() as tape:
tape.watch([w,b])
prob = tf.sigmoid(x @ w + b)
loss = tf.reduce_mean(tf.losses.MSE(y,prob))
grads = tape.gradient(loss,[w,b])
grads[0]
|