【问题标题】:Strange result when subtracting two tensors减去两个张量时的奇怪结果
【发布时间】:2021-10-09 08:24:10
【问题描述】:

我尝试减去两个张量,然后使用 relu 函数将每个负值转换为零,但我不能这样做,因为当我减去两个张量时,tensorflow 出于某种原因将 256 添加到每个负值!!

img = mpimg.imread('/home/moumenshobaky/tensorflow_files/virtualenv/archive/training/Dessert/82 
 7.jpg')
img2 = tf.math.floordiv(img,64)*64
img3 = img2-img
# showing an example of the Flatten class and operation
from tensorflow.keras.layers import Flatten
flatten = Flatten(dtype='float32')

print(flatten(img2))   
print(img3)

现在结果是

tf.Tensor(
[[ 0  0  0 ... 64 64  0]
[ 0  0  0 ... 64  0  0]
[64 64  0 ... 64  0  0]
...
[64 64 64 ... 64 64 64]
[64 64 64 ... 64 64 64]
[64 64 64 ... 64 64 64]], shape=(384, 1536), dtype=uint8)
tf.Tensor(
[[198 197 213 ... 229 252 202]
[194 193 207 ... 235 193 207]
[250 253 198 ... 238 193 207]
...
[227 217 207 ... 218 230 242]
[226 216 206 ... 217 230 239]
[225 215 203 ... 214 227 235]], shape=(384, 1536), dtype=uint8)

【问题讨论】:

  • 你是在减去负值,结果是加法吗?
  • no :/ 实际上,由于某种原因,这些值被添加到一个常量值,它是 256 我不知道为什么会发生这种情况

标签: tensorflow tensor


【解决方案1】:

我可以使用 tf.keras.utils.img_to_array 将图像转换为 numpy 数组以避免任何未知行为。

我使用了this image,我认为是同一个数据集。

img = mpimg.imread('C:/Users/as/Downloads/15.jpg')
img2 = tf.math.floordiv(img,64)*64

# convert to arrays
img = tf.keras.utils.img_to_array(img)
img2 = tf.keras.utils.img_to_array(img2)

img3 = img2-img
# showing an example of the Flatten class and operation
from tensorflow.keras.layers import Flatten
flatten = Flatten(dtype='float32')

print(flatten(img2))   
print(img3)

输出:

tf.Tensor(
[[192. 128.  64. ...   0.   0.   0.]
 [192. 128.  64. ...   0.   0.   0.]
 [192. 128. 128. ...   0.   0.   0.]
 ...
 [ 64.   0.   0. ...  64.   0.   0.]
 [ 64.   0.   0. ...  64.   0.   0.]
 [ 64.   0.   0. ...  64.   0.   0.]], shape=(512, 1536), dtype=float32)
[[[-17. -43. -58.]
  [-23. -51.  -3.]
  [-31. -61. -16.]
  ...
  [-20.  -7. -14.]
  [-20.  -7. -14.]
  [-20.  -7. -14.]]

 [[-19. -45. -60.]
  [-25. -53.  -5.]
  [-33. -63. -18.]
  ...
  [-20.  -7. -14.]
  [-20.  -7. -14.]
  [-21.  -8. -15.]]
 [[-21. -49.  -1.]
show more (open the raw output data in a text editor) ...
[-32. -31. -11.]
  ...
  [-30. -60. -15.]
  [-30. -60. -15.]
  [-30. -60. -15.]]]

出现问题是因为图像dtypeuint,它是无符号的,所以它不允许负值(检查类似的问题here)。

所以我发现你也可以使用 tf.cast(img, dtype=tf.float32) 解决问题。

【讨论】:

  • 太好了,非常感谢,但您知道为什么会发生这种情况吗?
  • @moumenShobakey 我更新了帖子以包含问题所在,以及另一个更简单的修复
  • 再次,太好了,我怀疑问题出在类型上,但我不知道 int8 是无符号的,谢谢分配
猜你喜欢
  • 2011-04-02
  • 1970-01-01
  • 2019-11-20
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多