测试神经网络模型时遇tf.equal类型不匹配错误求助
解决TensorFlow中tf.equal的类型不匹配错误
错误核心是tf.equal的两个输入数据类型不一致:prediction为int64类型,y_placeholder为int32类型,TensorFlow要求比较的两个张量必须同类型,因此需要统一二者的类型,以下是几种可行的解决方法:
方法一:修改占位符的定义类型
在定义y_placeholder时直接指定为int64类型,和prediction保持一致:
# 原定义若为tf.int32,改为tf.int64 y_placeholder = tf.placeholder(tf.int64, shape=[...])
方法二:将prediction转换为int32类型
在比较前用tf.cast把prediction转成和y_placeholder相同的int32类型:
# 修改correct_prediction这一行 correct_prediction = tf.equal(tf.cast(prediction, tf.int32), y_placeholder) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("Accuracy:", accuracy.eval({X_placeholder: X_test, y_placeholder: y_test}))
方法三:将y_placeholder转换为int64类型
反过来把y_placeholder转成int64类型,匹配prediction的类型:
# 修改correct_prediction这一行 correct_prediction = tf.equal(prediction, tf.cast(y_placeholder, tf.int64)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("Accuracy:", accuracy.eval({X_placeholder: X_test, y_placeholder: y_test}))
额外提示
如果项目可以迁移到TensorFlow 2.x,建议使用tf.keras的高层API(比如tf.keras.metrics.Accuracy),这类API会自动处理部分类型兼容问题,代码也更简洁。同时要确保训练集和测试集的标签数据类型统一,避免后续重复出现类似问题。
内容的提问来源于stack exchange,提问作者SoulSA
相关产品推荐
相关产品推荐

