我在具有tensorflow后端的keras中设置了具有K折交叉验证的自定义CNN。 在开始训练之前,将调用model.compile()函数,但是调用model.fit_generator()函数会导致运行时错误:“您必须在使用模型之前对其进行编译。”
我使用ImageDataGenerator进行数据增强,并使用fit_generator函数进行训练。
我直到现在才发现的唯一相关问题与tensorflow eager execution功能有关,该功能似乎未在Keras中启用。
代码如下:
模型定义:
model = Sequential()
model.add(Conv2D(24, (5, 5),
strides=(1, 1),
padding="valid",
data_format="channels_last",
activation='relu',
use_bias=True,
))#out=96
model.add(Dropout(.25))
model.add(MaxPooling2D(pool_size=(2, 2)))#out=48
model.add(Conv2D(32, (3, 3),
strides=(1, 1),
padding="valid",
data_format="channels_last",
activation='relu',
use_bias=True,
))#out=46
model.add(MaxPooling2D(pool_size=(2, 2)))#out=23
model.add(Conv2D(48, (3, 3),
strides=(1, 1),
padding="valid",
data_format="channels_last",
activation='relu',
use_bias=True,
))#out=21
model.add(MaxPooling2D(pool_size=(2, 2)))#padding???
model.add(Flatten())
model.add(Dense(3, activation='softmax'))
...这里是数据初始化...
设置ImageGenerator:
datagen_training = ImageDataGenerator(
rotation_range = 20,
width_shift_range = 0.3,
height_shift_range=0.3,
zoom_range=0.2,
fill_mode = "constant",
cval = 0,
vertical_flip = True,
validation_split = 0.2
)
datagen_training.fit(data)
模型设置和培训:
rmsprop = optimizers.RMSprop(lr=0.001)#docu says to only tune the learning rate
kf = KFold(n_splits=FOLDS, shuffle = True, random_state=78945)
model.compile(rmsprop, loss = losses.categorical_crossentropy, metrics=[metrics.categorical_accuracy])
acc_hist = []
while True:
history = object()
for train_idx, val_idx in kf.split(data, labels):
x_train, y_train = data[train_idx], labels[train_idx]
x_val, y_val = data[val_idx], labels[val_idx]
data_iterator = datagen_training.flow(x_train, y_train, batch_size=BATCH_SIZE)
history = model.fit_generator(data_iterator, steps_per_epoch=len(x_train) // BATCH_SIZE, epochs=1)
acc_hist.append(history.history['categorical_accuracy'][0])
#stop if accuracy doesn't change within 3 epochs
if stopping_criterion_met:
break
答案 0 :(得分:1)
由于未构建模型而未编译模型,并且由于未在第一层中指定input_shape
而未构建模型。我不确定您的数据的输入形状,但是对于您的第一层来说,像这样的东西将使模型得以编译:
model = Sequential()
model.add(Conv2D(24, (5, 5),
strides=(1, 1),
padding="valid",
data_format="channels_last",
activation='relu',
use_bias=True,
input_shape=(100,100,1)
))#out=96