在使用Keras的model.predict时遇到’index out of range’错误

这是我的代码,我正在使用迁移学习来训练我的模型。但是我遇到了索引超出范围的错误。这个错误发生在使用model.predict()函数测试我的模型时。可能的原因是什么?

IMAGE_SIZE = [100, 100]train_path = 'input/train'valid_path = 'input/val'

在VGG前添加预处理层

vgg = VGG16(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)# 不训练现有权重for layer in vgg.layers:  layer.trainable = False

用于获取类别数量

folders = glob('input/train/*')

我们的层

x = Flatten()(vgg.output)# x = Dense(1000, activation='relu')(x)prediction = Dense(len(folders), activation='softmax')(x)

创建模型对象

model = Model(inputs=vgg.input, outputs=prediction)

查看模型结构

model.summary()

告诉模型使用什么成本和优化方法

model.compile(  loss='categorical_crossentropy',  optimizer='adam',  metrics=['accuracy'])
from keras.preprocessing.image import ImageDataGeneratortrain_datagen = ImageDataGenerator(rescale = 1./255,                                   shear_range = 0.2,                                   zoom_range = 0.2,                                   horizontal_flip = True)test_datagen = ImageDataGenerator(rescale = 1./255)training_set = train_datagen.flow_from_directory('input/train',                                                 target_size = (100, 100),                                                 batch_size = 32,                                                 class_mode = 'categorical')val_set = test_datagen.flow_from_directory('input/val',                                            target_size = (100, 100),                                            batch_size = 32,                                            class_mode = 'categorical')

拟合模型

r = model.fit(  training_set,  validation_data=val_set,  epochs=50,  steps_per_epoch=len(training_set),  validation_steps=len(val_set))

这一行代码出现了错误

model.predict('/content/input/test/0/IMG_4099.JPG')

回答:

模型的predict方法不接受路径作为输入。根据文档,predict的输入样本可以是:

  • Numpy数组(或类似数组的对象),或多个数组的列表(如果模型有多个输入)。
  • TensorFlow张量,或多个张量的列表(如果模型有多个输入)。
  • tf.data数据集。
  • 生成器或keras.utils.Sequence实例。关于迭代器类型(数据集、生成器、序列)解包行为的更详细描述,请参见Model.fit中关于迭代器类型输入的解包行为部分。

有几种方法可以从图像路径中获得numpy数组。例如,你可以使用Keras预处理的image.load_img来读取图像,然后使用img_to_array获取numpy数组。如果文件夹中的图像大小不符合模型的预期,你将需要使用target_size参数调整到模型的输入形状。

img = tf.keras.preprocessing.image.load_img(    "/content/input/test/0/IMG_4099.JPG",    target_size=(100,100))img_nparray = tf.keras.preprocessing.image.img_to_array(img)type(img_nparray) # numpy.ndarrayinput_Batch = np.array([img_nparray])   # 将单张图像转换为批次.predictions = model.predict(input_Batch)

另一种方法是使用之前声明的图像generatortest_datagen,同样不进行数据增强以确保预测的公平性),指向包含该单张(或多张)图像的文件夹。

文件夹结构

├── content│   └── input│       └── test│           └── 0│               └── IMG_4099.JPG
import tensorflow as tffrom tensorflow import kerastest_datagen = ImageDataGenerator(rescale = 1./255)test_ImgGen = test_datagen.flow_from_directory(    '/content/input/test/0/',    target_size = (100, 100),    class_mode='categorical')model.predict(test_ImgGen)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注