【问题标题】:tf.reduce_sum() unexpected result with uint8tf.reduce_sum() 与 uint8 的意外结果
【发布时间】:2021-09-18 07:47:42
【问题描述】:

为什么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 的任何不兼容。

【问题讨论】:

    标签: python arrays numpy tensorflow tensor


    【解决方案1】:

    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,实际上是 @987654329 @。

    所以,它不在tf.reduce_sum(),它在uint8,并注意使用任何 dtype。

    【讨论】:

    • 感谢您的分解!我正在使用非常大的张量(例如(4, 400, 976, 976),因此选择uint8 是节省内存的明智选择。我非常有信心这应该可行,因为 numpy 通过自动向上转换为更大的整数来处理值范围溢出。我回到文档,确实提到了这种行为here
    猜你喜欢
    • 2018-03-21
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2012-04-02
    相关资源
    最近更新 更多