如何解决在keras中使用model.predict时,列表“索引超出范围”
这是我的代码,我正在使用转移学习来训练我的模型。但是我得到索引超出范围错误。当试图测试我的模型时,它给了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)
# don't train existing weights
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 ImageDataGenerator
train_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',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')
解决方法
模型predic
不接受路径作为输入。根据文档,predic输入样本可以是:
- 一个Numpy数组(或类似数组的数组)或一个数组列表(如果模型具有多个输入)。
- TensorFlow张量或张量列表(如果模型具有多个输入)。
- tf.data数据集。
- 生成器或keras.utils.Sequence实例。有关迭代器类型(数据集,生成器,序列)的拆包行为的详细说明,请参见Model.fit的类似迭代器的拆包行为部分。
有多种方法可以从图像路径获取numpy array
。例如,您可以使用Keras
预处理image.load_img
来读取图像,然后使用img_to_array
获得numpy array
。如果文件夹中的图像尚未达到模型所需的尺寸,则必须使用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.ndarray
input_Batch = np.array([img_nparray]) # Convert single image to a batch.
predictions = model.predict(input_Batch)
另一种替代方法是使用先前声明的图像generator
(test_datagen
,再次没有任何数据扩充以进行合理的预测),指向包含该单个(或多个)图像的文件夹
文件夹结构
├── content
│ └── input
│ └── test
│ └── 0
│ └── IMG_4099.JPG
import tensorflow as tf
from tensorflow import keras
test_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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。