You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:48:26