我正在尝试使用 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)
此代码取自并基于 the excellent example coremltools-keras-inception弄清楚后将进一步扩展。
最佳答案
发生此错误的原因是模型始终期望批量示例 - 而不是单个示例。这与将模型视为其输入的数学函数的普遍理解不同。模型期望批处理的原因是:
- 模型经过计算设计,可以更快地批量运行,从而加快训练速度。
- 有些算法会考虑输入的批量性质(例如 Batch Normalization 或 GAN 训练技巧)。
因此,四个维度来自第一个维度,即样本/批处理维度,然后 - 接下来的 3 个维度是图像暗淡。
关于machine-learning - 使用 TensorFlow 1.2.1 和 InceptionV3 对图像进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45041850/