Training a CNN using Keras, even though I did model.compile, keras. fit_generator throws a runtime error saying to do compile my model before using fit.

Error: 
Using TensorFlow backend.
WARNING:tensorflow:From C:\Users\..\Desktop\venvpy36\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
Found 468 images belonging to 2 classes.
Found 86 images belonging to 2 classes.
Traceback (most recent call last):
  File "C:/Users/../Desktop/miscfiles/template_classifier_cnn.py", line 75, in <module>
    model.fit_generator(train_generator)
  File "C:\Users\..\Desktop\venvpy36\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\..\Desktop\venvpy36\lib\site-packages\keras\engine\training.py", line 1418, in fit_generator
    initial_epoch=initial_epoch)
  File "C:\Users\..\Desktop\venvpy36\lib\site-packages\keras\engine\training_generator.py", line 40, in fit_generator
    model._make_train_function()
  File "C:\Users\..\Desktop\venvpy36\lib\site-packages\keras\engine\training.py", line 496, in _make_train_function
    raise RuntimeError('You must compile your model before using it.')
RuntimeError: You must compile your model before using it.

tried different optimizers, losses. tried building model without function.

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D,BatchNormalization
from keras.optimizers import Adam

import numpy as np
np.random.seed(1000)


train_datagen = ImageDataGenerator(
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=False
)


test_datagen = ImageDataGenerator(rescale=1./255)

def build_model():
    model = Sequential()
    model.add(Conv2D(32, (3, 3), padding='same'))
    model.add(Activation('relu'))
    model.add(Conv2D(32, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(BatchNormalization())
    model.add(Conv2D(64, (3, 3), padding='same'))
    model.add(Activation('relu'))
    model.add(Conv2D(64, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(512))
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(2))
    model.add(Activation('softmax'))


    model.compile(loss='categorical_crossentropy',
                  optimizer=Adam(0.001),
                  metrics=['accuracy'])
    return model

model = build_model()


train_generator = train_datagen.flow_from_directory(
        'data/images/template/cnn_train',
        target_size=(256,256),
        batch_size=32,
        class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
        'data/images/template/cnn_validate',
        target_size=(256,256),
        batch_size=32,
        class_mode='binary')
#model.summary()

model.fit_generator(train_generator)

1 Answers

1
Krunal Vaghani On Best Solutions

You have to assign input shape for your model, I think that is what it missing. Because in your Sequential() model you have not assigned input.

Here in your code model.add(Conv2D(32, (3, 3), padding='same')), for the first layer you have to assign input_shape.