【问题标题】:how to predict with pre-trained model in tensorflow?如何在张量流中使用预训练模型进行预测?
【发布时间】:2019-11-20 14:20:35
【问题描述】:

我是 TensorFlow 新手。我正在尝试从 github-https://github.com/Curt-Park/handwritten_digit_recognition 运行一个预训练的 NN 用于数字识别“wide_resnet_28_10”。当我尝试预测图像时,它说预期输入具有 4D。这是我尝试过的-

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

model = load_model(r'C:\Users\sesha\Desktop\python\Deep learning NN\handwritten_digit_recognition-master\models\WideResNet28_10.h5')
image = cv2.imread(r'C:\Users\sesha\Desktop\python\Deep learning NN\test_org01.png')
img = tf.convert_to_tensor(image)
predictions = model.predict([img])
print(np.argmax(predictions))

大多数教程都含糊不清,我确实尝试过 np.reshape(1,X,X,-1) 没有用。

【问题讨论】:

  • 你不需要img = tf.convert_to_tensor(image)

标签: python tensorflow


【解决方案1】:

对于 4D 输入,它需要批量数据。您可以通过以下方式使其成为 4D 张量:

predictions = model.predict(tf.expand_dims(img, 0))

如果这不起作用,请尝试 predict_on_batch 而不是 predict。

还有: 我不认为你的图像阅读是正确的。它可能会给你一个字节字符串的张量。

这应该可以工作

path = tf.constant(img_path)
image = tf.io.read_file(path)
image = tf.io.decode_image(image)
image = tf.image.resize(image, (X, Y)) # if necessary

【讨论】:

  • 第二个代码有效并且具有 (28,28,4) 但我仍然收到“ValueError:检查输入时出错:预期 input_1 有 4 个维度,但得到的数组形状为 (28, 28, 4)"
  • 你能运行model.summary()吗?并尝试打印 tf.expand_dims(img, 0) 的大小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多