微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – TensorFlow Tensor在numpy argmax vs keras argmax中的处理方式不同

为什么TensorFlow张量在Numpy中的数学函数中的表现与在Keras中的数学函数中表现不同?

当与TensorFlow Tensor处于相同的情况时,Numpy数组似乎正常运行.

这个例子表明在numpy函数和keras函数下正确处理numpy矩阵.

import numpy as np
from keras import backend as K

arr = np.random.rand(19, 19, 5, 80)

np_argmax = np.argmax(arr, axis=-1)
np_max = np.max(arr, axis=-1)

k_argmax = K.argmax(arr, axis=-1)
k_max = K.max(arr, axis=-1)

print('np_argmax shape: ', np_argmax.shape)
print('np_max shape: ', np_max.shape)
print('k_argmax shape: ', k_argmax.shape)
print('k_max shape: ', k_max.shape)

输出(如预期的那样)

np_argmax shape:  (19, 19, 5)
np_max shape:  (19, 19, 5)
k_argmax shape:  (19, 19, 5)
k_max shape:  (19, 19, 5)

与此示例相反

import numpy as np
from keras import backend as K
import tensorflow as tf

arr = tf.constant(np.random.rand(19, 19, 5, 80))

np_argmax = np.argmax(arr, axis=-1)
np_max = np.max(arr, axis=-1)

k_argmax = K.argmax(arr, axis=-1)
k_max = K.max(arr, axis=-1)

print('np_argmax shape: ', np_argmax.shape)
print('np_max shape: ', np_max.shape)
print('k_argmax shape: ', k_argmax.shape)
print('k_max shape: ', k_max.shape)

哪个输出

np_argmax shape:  ()
np_max shape:  (19, 19, 5, 80)
k_argmax shape:  (19, 19, 5)
k_max shape:  (19, 19, 5)
@H_404_36@解决方法:

您需要执行/运行代码(例如在TF会话下)以评估张量.在此之前,不评估张量的形状.

TF文档说:

Each element in the Tensor has the same data type, and the data type is always kNown. The shape (that is, the number of dimensions it has and the size of each dimension) might be only partially kNown. Most operations produce tensors of fully-kNown shapes if the shapes of their inputs are also fully kNown, but in some cases it’s only possible to find the shape of a tensor at graph execution time.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐