2016-11-13 105 views
1
import os 
from keras.preprocessing.image import ImageDataGenerator 
from keras.models import Sequential 
from keras.layers import Convolution2D, MaxPooling2D 
from keras.layers import Activation, Dropout, Flatten, Dense 

img_width, img_height = 64, 64 

train_data_dir = 'data/train' 
validation_data_dir = 'data/validation' 
nb_train_samples = sum([len(files) for files in os.walk(train_data_dir)]) 
nb_validation_samples = sum([len(files) for files in os.walk(validation_data_dir)]) 
nb_epoch = 10 


model = Sequential() 
model.add(Dense(4096, input_dim = 4096, init='normal', activation='relu')) 
model.add(Dense(4,init='normal',activation='softmax')) 
model.compile(loss='categorical_crossentropy', 
       optimizer='adam', 
       metrics=['accuracy']) 


train_datagen = ImageDataGenerator(
     rescale=1./255, 
     ) 


test_datagen = ImageDataGenerator(rescale=1./255) 

train_generator = train_datagen.flow_from_directory(
     train_data_dir, 
     color_mode="grayscale", 
     target_size=(img_width, img_height), 
     batch_size=1, 
     class_mode=None) 

validation_generator = test_datagen.flow_from_directory(
     validation_data_dir, 
     color_mode="grayscale", 
     target_size=(img_width, img_height), 
     batch_size=1, 
     class_mode=None) 

model.fit_generator(
     train_generator, 
     samples_per_epoch=nb_train_samples, 
     nb_epoch=nb_epoch, 
     validation_data=validation_generator, 
     nb_val_samples=nb_validation_samples) 

一切都运行良好,直到上面的代码中的model.fit_generator()。然后它会弹出如下所示的错误。model.fit_generator()形状错误

Traceback (most recent call last): 
    File "C:/Users/Sam/PycharmProjects/MLP/Testing Code without CNN.py", line 55, in <module> 
    nb_val_samples=nb_validation_samples) 
    File "C:\Python27\lib\site-packages\keras\models.py", line 874, in fit_generator 
    pickle_safe=pickle_safe) 
    File "C:\Python27\lib\site-packages\keras\engine\training.py", line 1427, in fit_generator 
    'or (x, y). Found: ' + str(generator_output)) 
Exception: output of generator should be a tuple (x, y, sample_weight) or (x, y). Found: [[[[ 0.19215688] 
+1

这段代码应该做什么?你能提供一些例子吗? –

回答

0

我不是100%肯定你想什么来实现,但如果你想图片的二元分类,尝试设置class_modebinary。来自documentation

class_mode:“categorical”,“binary”,“sparse”或None之一。默认值: “分类”。确定返回的标签数组的类型: “categorical”将是2D单热编码标签,“binary”将是1D 二进制标签,“稀疏”将是1D整数标签。

该错误消息是有点混乱,但如果你看看source code,它变得更清晰:

if not hasattr(generator_output, '__len__'): 
        _stop.set() 
        raise Exception('output of generator should be a tuple ' 
            '(x, y, sample_weight) ' 
            'or (x, y). Found: ' + str(generator_output)) 
+0

感谢您的回复!我试图根据列车和验证文件夹中的子文件夹对图像进行分类,并且共有4个子文件夹。我曾尝试使用无,分类和二进制的class_mode。没有提供上面的错误,而分类给出了这个错误。 >>异常:检查模型输入时出错:期望的dense_input_1有2个维度,但有形状的数组(1L,64L,64L,1L) 关于如何解决它的任何想法? – Weij

1

这个问题应该由数据尺寸不匹配造成的。 ImageDataGenerator实际加载图像文件并将其放入(num_image_channel,image_height,image_width)形状的numpy数组中。但是你的第一层是一个密集连接层,它正在寻找一维阵列形式的输入数据,或者寻找具有多个样本的二维阵列。所以基本上你会错过你的输入层,它会以正确的形状输入。

更改下面的代码行

model.add(Dense(4096, input_dim = 4096, init='normal', activation='relu')) 

model.add(Reshape((img_width*img_height*img_channel), input_shape=(img_channel, img_height, img_width))) 
model.add(Dense(4096, init='normal', activation='relu')) 

你必须定义img_channel,这是你的图像通道的数量。上述代码还假定您正在使用thdim_ordering。如果您正在使用tf输入维度排序,你就必须改变输入重塑层

model.add(Reshape((img_width*img_height*img_channel), input_shape=(img_height, img_width, img_channel))) 

---旧的答案 -

你可能已经把训练数据和验证数据到子文件夹下trainvalidation,这是Keras不支持的。所有培训数据应位于同一个文件夹中,对于验证数据也是如此。

详情请参阅this Keras tutorial

+0

[documentation](https://keras.io/preprocessing/image/)使用与问题中给出的代码相同的目录结构。 –

+0

这两行代码可能有问题。 'nb_train_samples = sum([len(files)for os in os in。步骤(train_data_dir)]) nb_validation_samples = sum([len(文件)for os.walk(validation_data_dir)]中的文件]' OP需要检查输出。 – pyan

+0

不要认为这应该是一个问题,它只是返回一个整数。 –