尝试在model.fit()

时间:2020-08-11 09:14:24

标签: python tensorflow keras cnn

# Define paths for image data
train_path = "C:/Users/dancu/PycharmProjects/firstCNN\data/ad-vs-cn/train"
test_path = "C:/Users/dancu/PycharmProjects/firstCNN\data/ad-vs-cn/test"
valid_path = "C:/Users/dancu/PycharmProjects/firstCNN\data/ad-vs-cn/valid"

# Use ImageDataGenerator to create 3 lots of batches
train_batches = ImageDataGenerator(
    rescale=1/255).flow_from_directory(directory=train_path,
        target_size=(256,240), classes=['cn', 'ad'], batch_size=10,
            color_mode="rgb")
valid_batches = ImageDataGenerator(
    rescale=1/255).flow_from_directory(directory=valid_path,
        target_size=(256,256), classes=['cn', 'ad'], batch_size=10,
            color_mode="rgb")
test_batches = ImageDataGenerator(
    rescale=1/255).flow_from_directory(directory=test_path,
        target_size=(256,256), classes=['cn', 'ad'], batch_size=10,
            color_mode="rgb")

imgs, labels = next(train_batches)

# Test to see normalisation has occurred properly
print(imgs[1][127])

# Define method to plot MRIs
def plotImages(images_arr):
    fig, axes = plt.subplots(1, 10, figsize=(20,20))
    axes = axes.flatten()
    for img, ax in zip( images_arr, axes):
        ax.imshow(img)
        ax.axis('off')
    plt.tight_layout()
    plt.show()

# Plot a sample of MRIs
plotImages(imgs)

# Define the model
model = Sequential([
    Conv2D(filters=32, kernel_size=(3, 3), activation='relu', padding = 'same', input_shape=(256,240,3)),
    MaxPool2D(pool_size=(2, 2), strides=2),
    Dropout(0.1),
    Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding='same'),
    MaxPool2D(pool_size=(2, 2), strides=2),
    Dropout(0.2),
    Conv2D(filters=128, kernel_size=(3, 3), activation='relu', padding='same'),
    MaxPool2D(pool_size=(2, 2), strides=2),
    Dropout(0.3),
    Flatten(),
    Dense(units=2, activation='softmax')
])

# Summarise each layer of the model
print(model.summary())

# Compile and train the model
model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x=train_batches,
    steps_per_epoch=len(train_batches),
    validation_data=valid_batches,
    validation_steps=len(valid_batches),
    epochs=35,
    verbose=1
)

错误消息:

最终确定GeneratorDataset迭代器时发生错误:失败的先决条件:Python解释器状态未初始化。该过程可以终止。 [[{{node PyFunc}}]]

关于问题可能在这里的任何想法?希望得到您的答复,我对CNN还是很陌生,所以这可能是我所缺少的一个非常明显的问题...

1 个答案:

答案 0 :(得分:0)

刚刚意识到这是因为我的ImageDataGenerator中的所有3个批次之间的输入形状都不相同...