python - tf.reduce_sum() uint8 出现意外结果

标签 python arrays numpy tensorflow tensor

为什么tf.reduce_sum()不适用于uint8

考虑这个例子:

>>> tf.reduce_sum(tf.ones((4, 10, 10), dtype=tf.uint8))
<tf.Tensor: shape=(), dtype=uint8, numpy=144>

>>> tf.reduce_sum(tf.ones((4, 10, 10), dtype=tf.uint16))
<tf.Tensor: shape=(), dtype=uint16, numpy=400>

有人知道这是为什么吗?

docs没有提到与 uint8 的任何不兼容性。

最佳答案

uint8 代表无符号整数,它使用 8 位来保存值。

通过8位,只能保存[0, 255]范围内的正数(无符号)(如果是int8则可以保存[-127,+127]范围内的有符号数) .

如果你想保留一个高于255的值,它只保留该数字的前8位,例如256 的二进制为 0000 0000 1,前 8 位为 0000 0000。因此,对于 256,您将得到 0 结果:

>>> tf.reduce_sum(tf.ones((1, 255), dtype=tf.uint8))
    <tf.Tensor: shape=(), dtype=uint8, numpy=255>

>>> tf.reduce_sum(tf.ones((1, 256), dtype=tf.uint8))
    <tf.Tensor: shape=(), dtype=uint8, numpy=0>

在您的例子中,预期结果是 400,但由于 uint8 无法保持高于 255 的值,因此当总和达到 256 时它将从 0 开始。因此,您看到的结果为 144实际上是 400-256=144

因此,它不在 tf.reduce_sum() 上,而是在 uint8 上,并注意使用任何数据类型。

关于python - tf.reduce_sum() uint8 出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68291540/

相关文章:

java - 如何使用 Java 加载图像并向其中写入文本?

python - Pandas :每行前 N 个非缺失值的总和

c++ - 在部分排序的数组中查找元素

php - INNER JOIN SQL/PHP - 需要单行且列上有数组

python - 使用 argsort 进行 Numpy 索引

python - 我可以使用应用服务中的 Azure 文件存储来存储然后读取/写入 SQLite 数据库吗?

python - 如何对 Pandas 的不规则时间间隔执行滚动平均值?

python - 以 Float 形式表示的年份到 Datetime64

python - 动态 Django 邮件配置

python - 将 NDArray 写入 JSON 和 .CV 文件