为什么uint8不能使用tf.reduce_sum()?
考虑这个例子:
>>> 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的任何不兼容。
发布于 2021-07-08 03:17:42
uint8代表unsigned integer,它获取8位以保持值。
通过8位,您只能在范围0, 255中保存正数(无符号)。
如果你想保持一个大于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上,注意使用任何数据类型。
https://stackoverflow.com/questions/68291540
复制相似问题