如何将 Tensor 转换为 NumPy 数组

How to convert Tensor into NumPy array

我已经根据我的数据训练了 ResNet50 模型。我想在进行预测时获得自定义层的输出。我尝试使用下面的代码来获取自定义层的输出,它以张量格式提供数据,但我需要 NumPy array 格式的数据。我尝试将张量转换为 NumPy 数组但出现错误,我已按照此 ,但没有帮助

谁能分享一些想法,任何建议都会很有帮助

from keras.models import load_model
import tensorflow as tf
import numpy as np

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.Session(config=config)

model = load_model(model_path) # load trained model

data = load_data(data_path) # load data for predictions
result = model.predict(data)
print(type(result_dev))
#<class 'numpy.ndarray'> 

result = model.get_layer('avg_pool').output
print(type(result))
#<class 'tensorflow.python.framework.ops.Tensor'>

我尝试过的事情

选项 1

result = result.numpy()

AttributeError: 'Tensor' object has no attribute 'numpy'

选项 2

result = result.eval(session=tf.compat.v1.Session())

2020-09-22 11:21:59.522138: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-09-22 11:21:59.522343: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties:

已安装的依赖项:

tensorflow-gpu==1.15.0

您只能在 Eager 执行期间将张量转换为 numpy 数组。由于您使用的版本早于 2.0,因此默认情况下未启用。

无论如何,你可以在导入tensorflow之后调用这个:

tf.compat.v1.enable_eager_execution()

根据您的框架和用例,您可能还必须 运行 tf.config.run_functions_eagerly(如果您在任何地方定义了 tf.function)。为了更好地支持 Eager 模式,您应该将 tensorflow 升级到最新版本并使用 tf.keras,因为您的代码可能无法与旧的独立版本 Keras 一起正常工作。在较新的版本中,您可以像这样急切地将您的 keras 模型指定为 运行:

model.run_eagerly = True

可以使用以下 tensorflow 函数将 tensor 转换为 numpy 数组:

import tensorflow as tf
tf.make_ndarray(
    tensor
)

例如:

# Tensor a has shape (2,3)
a = tf.constant([[1,2,3],[4,5,6]])
proto_tensor = tf.make_tensor_proto(a)  # convert `tensor a` to a proto tensor
tf.make_ndarray(proto_tensor) # output: array([[1, 2, 3],
#                                              [4, 5, 6]], dtype=int32)
# output has shape (2,3)

最后提到的方法 here 对我有用 tensorflow-gpu==2.0.0keras==2.2.4