如何编译Keras CNN模型并使用fit_generator方法?

时间:2019-03-31 06:56:24

标签: python machine-learning keras deep-learning conv-neural-network

我正在尝试对猫和猫进行分类,但这给了我关于编译的错误 尽管我已经编译了模型,但是仍然出现错误,提示我在尝试使用fit_generator时需要先编译模型 请帮忙!!!!!!!!

classifier = Sequential()

classifier.add(Convolution2D(filters = 32, kernel_size = [3,3], padding = 'SAME', activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

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('dataset/training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary')
test_set = test_datagen.flow_from_directory('dataset/test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary')

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

classifier.fit_generator(training_set, steps_per_epoch = 8000, epochs = 25, validation_data = test_set, validation_steps = 2000)
RuntimeError                              Traceback (most recent call last)
<ipython-input-13-98e5035b2986> in <module>
----> 1 classifier.fit_generator(training_set, steps_per_epoch = 8000, epochs = 25, validation_data = test_set, validation_steps = 2000)

~\AppData\Local\conda\conda\envs\TensorFlow\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name + '` call to the ' +
     90                               'Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

~\AppData\Local\conda\conda\envs\TensorFlow\lib\site-packages\keras\engine\training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   1416             use_multiprocessing=use_multiprocessing,
   1417             shuffle=shuffle,
-> 1418             initial_epoch=initial_epoch)
   1419 
   1420     @interfaces.legacy_generator_methods_support

~\AppData\Local\conda\conda\envs\TensorFlow\lib\site-packages\keras\engine\training_generator.py in fit_generator(model, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
     38 
     39     do_validation = bool(validation_data)
---> 40     model._make_train_function()
     41     if do_validation:
     42         model._make_test_function()

~\AppData\Local\conda\conda\envs\TensorFlow\lib\site-packages\keras\engine\training.py in _make_train_function(self)
    494     def _make_train_function(self):
    495         if not hasattr(self, 'train_function'):
--> 496             raise RuntimeError('You must compile your model before using it.')
    497         self._check_trainable_weights_consistency()
    498         if self.train_function is None:

RuntimeError: You must compile your model before using it.

2 个答案:

答案 0 :(得分:0)

您没有在模型中提及输入形状

classifier.add(Convolution2D(filters = 32, kernel_size = [3,3], padding =         'SAME', activation = 'relu',input_shape=(64, 64, 3)))

答案 1 :(得分:0)

您必须将输入形状赋予第一层,以便模型能够编译或创建模型图。以此将输入形状添加到模型的第一层

classifier.add(Convolution2D(filters = 32, kernel_size = [3,3], **Input_Shape=(64,64,3)** , padding = 'SAME', activation = 'relu'))

比在编译完模型之后,查看模型摘要。这表明您的模型将像

那样完全编译成功
  classifier.summary()

完整代码:

classifier = Sequential()

classifier.add(Convolution2D(filters = 32, kernel_size = [3,3], Input_Shape=(64,64,3) , padding = 'SAME', activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

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('dataset/training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary')
test_set = test_datagen.flow_from_directory('dataset/test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary')

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
classifier.summary()
classifier.fit_generator(training_set, steps_per_epoch = 8000, epochs = 25, validation_data = test_set, validation_steps = 2000)

这样做可以解决您的问题:)