TensorFlow代码报错:bool类型不在Sum算子允许类型列表,求修复
问题修复:TensorFlow中
tf.reduce_sum无法处理bool类型张量 错误原因
报错信息明确指出tf.reduce_sum不支持bool类型输入。你的代码中(pred == i) & (target == i)生成的是bool类型张量,直接传给tf.reduce_sum触发了类型不匹配错误。
修复方案
有两种简单的解决方式:
方法1:将bool张量转换为数值类型
把比较后的bool结果转为tf.int64(或其他支持的数值类型),再进行求和:
import tensorflow as tf import numpy as np out = [] num_classes = 1 for i in tf.range(num_classes): pred = tf.random.uniform(shape=[800]) target = tf.random.uniform(shape=[800]) pred = tf.cast(pred, tf.int64) target = tf.cast(target, tf.int64) i = tf.cast(i, tf.int64) # 将bool结果转为int64后求和 match = tf.cast((pred == i) & (target == i), tf.int64) out.append(tf.reduce_sum(match)) b = tf.stack(out)
方法2:使用tf.math.count_nonzero直接统计匹配数量
如果你的需求是统计True的个数,用tf.math.count_nonzero更直接,无需手动转换类型:
import tensorflow as tf import numpy as np out = [] num_classes = 1 for i in tf.range(num_classes): pred = tf.random.uniform(shape=[800]) target = tf.random.uniform(shape=[800]) pred = tf.cast(pred, tf.int64) target = tf.cast(target, tf.int64) i = tf.cast(i, tf.int64) # 直接统计True的数量 out.append(tf.math.count_nonzero((pred == i) & (target == i))) b = tf.stack(out)
补充说明
tf.random.uniform默认生成float32类型的随机数,你转成int64后所有值都会变成0(因为随机数范围默认是[0,1),截断为整数就是0),如果这不是你预期的结果,建议调整tf.random.uniform的minval和maxval参数,比如:
这样可以直接生成指定范围的整数,省去后续类型转换步骤。pred = tf.random.uniform(shape=[800], minval=0, maxval=num_classes, dtype=tf.int64) target = tf.random.uniform(shape=[800], minval=0, maxval=num_classes, dtype=tf.int64)
内容的提问来源于stack exchange,提问作者Anshuman Sinha
相关产品推荐
相关产品推荐

