[英]How to convert Tensor into NumPy array
我已经根据我的数据训练ResNet50
model。 我想在进行预测时获得自定义层的 output。 我尝试使用以下代码获取自定义层的 output,它以张量格式提供数据,但我需要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'>
我试过的东西
result = result.numpy()
AttributeError: 'Tensor' object 没有属性 'numpy'
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] 从 SysFS 读取成功的 NUMA 节点有负值(-1),但必须至少有一个 NUMA 节点,所以返回NUMA 节点零 2020-09-22 11:21:59.522343: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] 找到具有属性的设备 0:
依赖安装:
tensorflow-gpu==1.15.0
在 Eager 执行期间,您只能将张量转换为 numpy arrays。 由于您使用的版本早于 2.0,因此默认情况下未启用。
在任何情况下,您都可以在导入 tensorflow 后调用它:
tf.compat.v1.enable_eager_execution()
根据您的框架和用例,您可能还必须运行tf.config.run_functions_eagerly
(如果您在任何地方定义了tf.function
)。 为了更好地支持 Eager 模式,您应该将 tensorflow 升级到最新版本并使用tf.keras
,因为您的代码可能无法与Keras
的旧独立版本一起正常工作。 在较新的版本中,您可以指定您的 keras model 像这样急切地运行:
model.run_eagerly = True
可以使用以下 tensorflow 的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)
最后这里提到的方法对我tensorflow-gpu==2.0.0
和keras==2.2.4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.