【问题标题】:How to convert Tensor into NumPy array如何将张量转换为 NumPy 数组
【发布时间】:2021-01-08 06:24:37
【问题描述】:

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

任何人都可以分享一些想法,任何建议都会非常有帮助

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' 对象没有属性 'numpy'

选项 2

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

2020-09-22 11:21:59.522138: 我 tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] 成功 从 SysFS 读取的 NUMA 节点具有负值 (-1),但必须有 至少一个 NUMA 节点,所以返回 NUMA 节点为零 2020-09-22 11:21:59.522343:我 tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] 找到设备 0 带属性:

已安装依赖项:

tensorflow-gpu==1.15.0

【问题讨论】:

    标签: python numpy tensorflow tensor


    【解决方案1】:

    您只能在 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
    

    【讨论】:

    • 我尝试使用 tf.enable_eager_execution() 启用急切执行,但它会引发错误 RuntimeError: get_session is not available when TensorFlow is executing eagerly.。我也尝试过tensorflow-gpu==2.0,但是由于模型是在tensorflow-gpu==1.15 上进行训练的,因此在使用tensorflow-gpu==2.0 加载它时会抛出错误
    • 我期待这个,因此我的警告。这些旧版本的兼容性很棘手(参见例如here),我无法直接帮助您,因为它是非常特定于项目的,并且需要一些试验和错误,直到您找到正确的包组合。无论如何,我的回答是:如果你想使用 Eager,这就是你通常的做法。
    【解决方案2】:

    使用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)
    
    

    【讨论】:

    • tf.make_ndarray(tensor) 抛出此错误AttributeError: 'Tensor' object has no attribute 'tensor_shape'
    • 以上链接如何帮助解决OP的问题?
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-17
      • 2018-11-28
      • 2019-06-13
      • 2019-03-19
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多