【发布时间】:2018-05-27 12:01:03
【问题描述】:
我正在使用带有 tensorflow 后端的 keras 为两个类编写图像分类代码。我的图像存储在计算机的文件夹中,我想将这些图像作为我的 keras 模型的输入。 load_img 只接受一个输入图像,所以我必须使用flow(x,y) 或flow_from_directory(directory),但在flow(x,y) 中,我们还需要提供长度任务的标签,所以我使用flow_from_directory(directory)。我的图像尺寸可变,例如 20*40、55*43 ..... 但是here 提到需要固定的 target_size。在this 解决方案中,我们可以使用input_shape=(1, None, None) 或 input_shape=(None,None,3) (通道最后和彩色图像)将可变大小的图像作为卷积层的输入,但 fchollet 提到它对展平层和我的模型包括卷积层和展平层。在那篇文章中,只有 moi90 建议尝试不同的批次,但每个批次应该有相同大小的图像,但我不可能对相同大小的图像进行分组,因为我的数据非常分散。所以我决定使用batch size=1 并编写以下代码:
from __future__ import print_function
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
input_shape = (None,None,3)
model = Sequential()
model.add(Conv2D(8, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.get_weights()
model.add(Conv2D(16, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))
model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy'])
train_datagen = ImageDataGenerator()
test_datagen = ImageDataGenerator()
train_generator = train_datagen.flow_from_directory('/data/train', target_size=input_shape, batch_size=1,class_mode='binary')
validation_generator = test_datagen.flow_from_directory('/data/test',target_size=input_shape,batch_size=1,class_mode='binary')
model.fit_generator(train_generator,steps_per_epoch=1,epochs=2,validation_data=validation_generator,validation_steps=1)
现在我收到以下错误:
Traceback (most recent call last):
File "<ipython-input-8-4e22d22e4bd7>", line 23, in <module>
model.add(Flatten())
File "/home/nd/anaconda3/lib/python3.6/site-packages/keras/models.py", line 489, in add
output_tensor = layer(self.outputs[0])
File "/home/nd/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 622, in __call__
output_shape = self.compute_output_shape(input_shape)
File "/home/nd/anaconda3/lib/python3.6/site-packages/keras/layers/core.py", line 478, in compute_output_shape
'(got ' + str(input_shape[1:]) + '. '
ValueError: The shape of the input to "Flatten" is not fully defined (got (None, None, 16). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.
我确定这不是因为 img_dim_ordering 和 backend 而是因为 this 我已经检查过两者都是 th 请帮助纠正他的代码或帮助我如何将可变大小的图像作为输入我的模型。
【问题讨论】:
-
等待更多正确答案
标签: image-processing machine-learning neural-network deep-learning keras