减去两个张量时的奇怪结果

Strange result when subtracting two tensors

我尝试减去两个张量,然后使用 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)

我可以使用 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.]]]

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

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