TensorFlow 1.2.1和InceptionV3用于对图像进行分类。

3

我正在尝试使用Google最新版本的TensorFlow中内置的Keras创建一个示例。该示例应该能够对经典的大象图像进行分类。代码如下:

# Import a few libraries for use later
from PIL import Image as IMG

from tensorflow.contrib.keras.python.keras.preprocessing import image
from tensorflow.contrib.keras.python.keras.applications.inception_v3 import InceptionV3
from tensorflow.contrib.keras.python.keras.applications.inception_v3 import preprocess_input, decode_predictions


# Get a copy of the Inception model
print('Loading Inception V3...\n')
model = InceptionV3(weights='imagenet', include_top=True)
print ('Inception V3 loaded\n')

# Read the elephant JPG
elephant_img = IMG.open('elephant.jpg')

# Convert the elephant to an array
elephant = image.img_to_array(elephant_img)
elephant = preprocess_input(elephant)

elephant_preds = model.predict(elephant)

print ('Predictions: ', decode_predictions(elephant_preds))

很不幸,在尝试使用model.predict评估模型时,我遇到了一个错误:

ValueError: Error when checking : expected input_1 to have 4 dimensions, but got array with shape (299, 299, 3)

这段代码基于coremltools-keras-inception优秀的示例,并在后续进一步扩展。


请问您能否分享完整的回溯信息? - Ofer Sadan
如果您仍然需要,我可以提供参考,但是答案已经解释了发生了什么,并且我明确指出了哪一行失败了。 - Tom T
我现在看到你发布了一个答案,干得好,忽略我的上一条评论 :) - Ofer Sadan
2个回答

3
出现这个错误的原因是模型总是期望一批示例,而不是单个示例。这与将模型视为其输入的数学函数的常见理解不同。模型期望批处理的原因是:
  1. 模型在设计时计算能力被优化为在批处理上更快速地工作以加速训练。
  2. 有些算法考虑了输入的批处理特性(例如批归一化GAN训练技巧)。
因此,四个维度来自第一个维度,即样本/批次维度,然后是下一个三个维度是图像维度。

2

实际上我找到了答案。尽管文档说明如果包含顶层,则输入向量的形状仍然设置为批量图像。因此,在预测代码行之前,我们需要添加以下内容:

elephant = numpy.expand_dims(elephant, axis=0)

那么张量的形状就正确了,一切都可以正常工作。我仍然不确定为什么文档中指出输入向量应该是(3x299x299)或(299x299x3),当它明显需要4个维度。

要小心!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接