WARNING:tensorflow:The dtype of the target tensor must be floating

本文详细阐述了如何在使用TensorFlow进行梯度计算时遇到`target tensor must be floating`错误,并提供了两种解决方案:一是将常量y转换为浮点32,二是调整MSE损失函数的输入顺序。通过实例代码演示了修复过程。
摘要由CSDN通过智能技术生成

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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值