Machine learning TensorFlow 1.2.1和InceptionV3对图像进行分类

Machine learning TensorFlow 1.2.1和InceptionV3对图像进行分类,machine-learning,tensorflow,neural-network,keras,coreml,Machine Learning,Tensorflow,Neural Network,Keras,Coreml,我正在尝试使用谷歌最新版本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.

我正在尝试使用谷歌最新版本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评估模型时出错。predict:

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

这段代码取自并基于它,当它被计算出来时,将被进一步扩展。

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

elephant = numpy.expand_dims(elephant, axis=0)
然后张量的形状正确,一切都正常。我仍然不确定为什么文档中规定输入向量应该是(3x299x299)或(299x299x3),而它显然需要4维


小心

发生此错误的原因是,模型总是希望得到示例,而不是单个示例。这与将模型视为其输入的数学函数的共识不同。模型需要批次的原因如下:

  • 模型经过计算设计,可以更快地批量工作,从而加快培训速度
  • 有些算法考虑了输入的批量性质(例如,或GAN训练技巧)

  • 因此,四个维度来自第一个维度,这是一个样本/批次维度,然后-接下来的三个维度是图像DIM。

    你能分享整个回溯吗?如果你还想的话,我可以把它作为参考,但答案解释了发生了什么,我提到了哪一行失败。我现在明白了贴出答案,干得好,忽略我的最后一个:)