gpt4 book ai didi

python - TensorFlow Tensor 在 numpy argmax 与 keras argmax 中的处理方式不同

转载 作者:太空狗 更新时间:2023-10-30 02:37:56 26 4
gpt4 key购买 nike

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

Numpy 数组在与 TensorFlow Tensor 相同的情况下似乎表现正常。

此示例表明在 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)

最佳答案

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

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.

关于python - TensorFlow Tensor 在 numpy argmax 与 keras argmax 中的处理方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48615667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com