Tensorflow error(二):x and y must have the same dtype, got tf.float32 != tf.int32

简介: 本文讨论了TensorFlow中的一个常见错误,即在计算过程中,变量的数据类型(dtype)不一致导致的错误,并通过使用`tf.cast`函数来解决这个问题。

原代码

    with tf.GradientTape() as tape:
        # 打平操作,[b, 28, 28] => [b, 784]
        x = tf.reshape(x, (-1, 28*28))
        # Step1. 得到模型输出output [b, 784] => [b, 10]
        out = model(x)
        # [b] => [b, 10]
        y_onehot = tf.one_hot(y, depth=10)
        # 计算差的平方和,[b, 10]
        loss = tf.square(out-y_onehot)
        # 计算每个样本的平均误差,[b] x.shape[0]相当于N
        loss = tf.reduce_sum(loss) / x.shape[0]

错图:
在这里插入图片描述
错因:除数和被除数的数据类型不一致

解决方式:将x.shape[0]通过tf.cast改变数据类型即可

  • loss = tf.reduce_sum(loss) / x.shape
    改为
    X = tf.cast(x.shape[0],dtype=float)
    loss = tf.reduce_sum(loss) / X

在这里插入图片描述
觉得有用请留下你的赞 ^__^

目录
相关文章
|
11月前
【深入理解计算机系统】int 不是整数 | float 不是实数 | 内存引用错误的例子 | 学习笔记
【深入理解计算机系统】int 不是整数 | float 不是实数 | 内存引用错误的例子 | 学习笔记
66 0
|
1天前
|
并行计算 TensorFlow 算法框架/工具
Tensorflow error(三):failed to get convolution algorithm,cuDNN failed to initialize
这篇文章讨论了TensorFlow在进行卷积操作时可能遇到的“failed to get convolution algorithm”错误,通常由于cuDNN初始化失败引起,并提供了几种解决方案,包括调整GPU内存使用策略和确保CUDA、cuDNN与TensorFlow版本兼容性。
9 1
Tensorflow error(三):failed to get convolution algorithm,cuDNN failed to initialize
|
2月前
|
TensorFlow 算法框架/工具 iOS开发
【Python-Tensorflow】ERROR: Could not find a version that satisfies the requirement tensorflow
本文讨论了在安装TensorFlow时遇到的版本兼容性问题,并提供了根据Python版本选择正确pip版本进行安装的解决方法。
205 1
|
3月前
|
存储 数据处理 索引
数据类型转换:int()、str()、float()
在Python中,数据类型转换是一项基础且重要的操作
|
3月前
|
存储 Python
语音输入,python数据类型,type()用来查看数据类型,数据类型转换,int(x)转整数,float(x)转换为浮点数,str(x),将对象转为字符串,标识符,标识符不允许使用关键字,关键字参考
语音输入,python数据类型,type()用来查看数据类型,数据类型转换,int(x)转整数,float(x)转换为浮点数,str(x),将对象转为字符串,标识符,标识符不允许使用关键字,关键字参考
|
5月前
|
存储 C语言
计算 int, float, double 和 char 字节大小
计算 int, float, double 和 char 字节大小。
70 3
|
12月前
|
存储 C语言
C 语言实例 - 计算 int, float, double 和 char 字节大小
C 语言实例 - 计算 int, float, double 和 char 字节大小。
86 1
|
5月前
牛客网刷题总结1.利用%符号获取特定位数的数字。2.强制类型转换 (将float转换为int )3.计算有关浮点型数据时,要注意你计算过程中所有的数据都是浮点型
牛客网刷题总结1.利用%符号获取特定位数的数字。2.强制类型转换 (将float转换为int )3.计算有关浮点型数据时,要注意你计算过程中所有的数据都是浮点型
59 0
|
11月前
|
存储 C语言
计算 int, float, double 和 char 字节大小
C 语言实例 - 计算 int, float, double 和 char 字节大小。
83 1
对int,char,float,double进行求和操作
对int,char,float,double进行求和操作
162 0