gpt4 book ai didi

python - 为什么 keras 模型编译但 fit_generator 命令抛出 'model not compiled runtime error' ?

转载 作者:行者123 更新时间:2023-11-28 18:06:35 24 4
gpt4 key购买 nike

我已经在带有 tensorflow 后端的 keras 中设置了一个带有 K 折交叉验证的自定义 CNN。model.compile() 函数在开始训练之前被调用,但是 model.fit_generator() 函数调用导致运行时错误:“You must compile your model before using it.”

我使用 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'))

...这里将是数据初始化...

设置图像生成器:

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

最佳答案

模型未编译是因为它未被构建,它未被构建是因为 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

关于python - 为什么 keras 模型编译但 fit_generator 命令抛出 'model not compiled runtime error' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com