TensorFlow 2.x中非eagerTensor类型Tensor转换为Numpy数组问题问询
TensorFlow 2.x 非eager张量转numpy数组解决方案
错误原因
你现有代码中取到的model.get_layer(name='prediction_image').output是模型计算图的静态张量节点,没有绑定实际前向计算的数值,不属于eagerTensor类型,因此直接调用.numpy()方法无效。你之前调用的model.predict(x_ds)没有保存结果,也没有和目标层的输出做关联。
推荐解决方法(适配TF2原生逻辑)
构造截取到目标层输出的子模型,直接通过predict方法得到numpy格式的层输出:
# 原有预处理代码不变 img_height=330 img_width=600 img_depth=23 save_model="saved_Models/wheatModel" prediction_data_path=["data/stacked/MOD13Q1.A2017.2738.tif","data/stacked/MOD13Q1.A2017.889.tif","data/stacked/MOD13Q1.A2017.923.tif"] prediction_data=dataConv.preparePredictionData(prediction_data_path) prediction_reshaped=dataConv.reshapeFiles(prediction_data,img_width,img_height,img_depth) x_ds =tf.stack(prediction_reshaped) # 加载原模型 model = tf.keras.models.load_model(save_model) # 构造子模型:输入为原模型输入,输出为目标层的输出 feature_extractor = tf.keras.Model( inputs=model.input, outputs=model.get_layer(name='prediction_image').output ) # 直接预测得到numpy数组格式的层输出 layer_output = feature_extractor.predict(x_ds) # 做维度调整即可,此时已经是numpy数组可以直接操作 n,output_width,output_height,output_depth,output_channels = layer_output.shape image = layer_output.reshape((output_width,output_height,output_depth))
兼容型解决方法(不推荐)
如果需要沿用原有计算图节点逻辑,可以调用TF1兼容接口的会话执行得到数值:
# 原有代码执行到reshape之后 image=tf.reshape(image,(output_width,output_height,output_depth)) with tf.compat.v1.Session() as sess: # 加载模型权重到会话中 tf.compat.v1.keras.backend.set_session(sess) sess.run(tf.compat.v1.global_variables_initializer()) # 传入输入数据执行计算得到numpy数组 image_np = sess.run(image, feed_dict={model.input: x_ds})
注意事项
- 推荐第一种方法,完全适配TensorFlow 2.x的eager执行逻辑,不需要依赖废弃接口,稳定性和执行效率更高
- 建议先拿到层输出的实际数值后再做维度调整,避免计算图节点操作带来的额外开销
内容的提问来源于stack exchange,提问作者lutz500
相关产品推荐
相关产品推荐

