首页 文章

在resnet50转移学习期间大量过度适应

提问于
浏览
5

这是我第一次尝试与CNN做某事,所以我可能做了一些非常愚蠢的事 - 但无法弄清楚我错在哪里......

该模型似乎学得很好,但验证准确性没有提高(甚至在第一个时期之后),验证损失实际上随着时间的推移而增加 . 它看起来并不像我过度使用(在1个纪元之后?) - 我们必须以其他方式关闭 .

typical network behaviour

我正在训练一个CNN网络 - 我有~100k各种植物的图像(1000个类),并希望微调ResNet50以创建一个muticlass分类器 . 图像有各种尺寸,我加载它们如下:

from keras.preprocessing import image                  

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(IMG_HEIGHT, IMG_HEIGHT))
    # convert PIL.Image.Image type to 3D tensor with shape (IMG_HEIGHT, IMG_HEIGHT, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, IMG_HEIGHT, IMG_HEIGHT, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in img_paths] #can use tqdm(img_paths) for data
    return np.vstack(list_of_tensors)enter code here

数据库很大(不适合内存),必须创建自己的生成器,以提供磁盘读取和扩充 . (我知道Keras有.flow_from_directory() - 但我的数据不是这样构建的 - 它只是一个100k图像与100k元数据文件混合的转储) . 我可能应该创建一个脚本来更好地构造它们而不是创建我自己的生成器,但问题可能在其他地方 .

下面的生成器版本暂时不进行任何扩充 - 只需重新缩放:

def generate_batches_from_train_folder(images_to_read, labels, batchsize = BATCH_SIZE):    

    #Generator that returns batches of images ('xs') and labels ('ys') from the train folder
    #:param string filepath: Full filepath of files to read - this needs to be a list of image files
    #:param np.array: list of all labels for the images_to_read - those need to be one-hot-encoded
    #:param int batchsize: Size of the batches that should be generated.
    #:return: (ndarray, ndarray) (xs, ys): Yields a tuple which contains a full batch of images and labels. 

    dimensions = (BATCH_SIZE, IMG_HEIGHT, IMG_HEIGHT, 3)

    train_datagen = ImageDataGenerator(
        rescale=1./255,
        #rotation_range=20,
        #zoom_range=0.2, 
        #fill_mode='nearest',
        #horizontal_flip=True
    )

    # needs to be on a infinite loop for the generator to work
    while 1:
        filesize = len(images_to_read)

        # count how many entries we have read
        n_entries = 0
        # as long as we haven't read all entries from the file: keep reading
        while n_entries < (filesize - batchsize):

            # start the next batch at index 0
            # create numpy arrays of input data (features) 
            # - this is already shaped as a tensor (output of the support function paths_to_tensor)
            xs = paths_to_tensor(images_to_read[n_entries : n_entries + batchsize])

            # and label info. Contains 1000 labels in my case for each possible plant species
            ys = labels[n_entries : n_entries + batchsize]

            # we have read one more batch from this file
            n_entries += batchsize

            #perform online augmentation on the xs and ys
            augmented_generator = train_datagen.flow(xs, ys, batch_size = batchsize)

        yield  next(augmented_generator)

这就是我定义模型的方式:

def get_model():

    # define the model
    base_net = ResNet50(input_shape=DIMENSIONS, weights='imagenet', include_top=False)

    # Freeze the layers which you don't want to train. Here I am freezing all of them
    for layer in base_net.layers:
        layer.trainable = False

    x = base_net.output

    #for resnet50
    x = Flatten()(x)
    x = Dense(512, activation="relu")(x)
    x = Dropout(0.5)(x)
    x = Dense(1000, activation='softmax', name='predictions')(x)

    model = Model(inputs=base_net.input, outputs=x)

    # compile the model 
    model.compile(
        loss='categorical_crossentropy',
        optimizer=optimizers.Adam(1e-3),
        metrics=['acc'])

    return model

因此,对于大约70k图像,我有1,562,088个可训练参数

然后我使用5倍交叉验证,但模型不适用于任何折叠,所以我不会在这里包含完整代码,相关位是这样的:

trial_fold = temp_model.fit_generator(
                train_generator,
                steps_per_epoch = len(X_train_path) // BATCH_SIZE,
                epochs = 50,
                verbose = 1,
                validation_data = (xs_v,ys_v),#valid_generator,
                #validation_steps= len(X_valid_path) // BATCH_SIZE,
                callbacks = callbacks,
                shuffle=True)

我做了各种各样的事情 - 确保我的发电机实际工作,试图通过减少完全连接层的大小来玩网络的最后几层,尝试增加 - 没有任何帮助......

我不认为网络中的参数数量太大 - 我知道其他人做了几乎相同的事情,准确度接近0.5,但我的模型似乎过于逼近疯狂 . 任何有关如何解决这个问题的想法将不胜感激!

Update 1:

我决定停止重新发送东西并按文件排序以使用.flow_from_directory()过程 . 为了确保我输入正确的格式(由下面的Ioannis Nasios评论引发) - 我确保来自keras的resnet50应用程序的preprocessing_unit() .

我还决定检查模型是否实际上产生了一些有用的东西 - 我为我的数据集计算了botleneck特征,然后使用随机森林来预测类 . 它确实有效,我的准确度大约为0.4

所以,我想我的图像输入格式确实存在问题 . 下一步,我将微调模型(使用新的顶层)以查看问题是否仍然存在......

Update 2:

我认为问题出在图像预处理上 . 我最终没有进行微调,只是提取了botleneck层并训练了linear_SVC() - 得到了大约60%的列车精度和大约45%的测试数据集 .

5 回答

  • 1

    我也在研究一个非常小的数据集,虽然训练准确性越来越高,但遇到了同样的问题,即验证准确性仍然存在 . 我还注意到,随着时间的推移,我的验证损失也越来越高 . 仅供参考,我使用的是Resnet 50和InceptionV3型号 .

    在互联网上进行了一些挖掘之后,我发现了一个关于github的讨论,它将这个问题与Keras中的Batch Normalization层的实现联系起来 . 在应用转移学习和微调网络时遇到上述问题 . 我不确定您是否遇到同样的问题,但我已将下面的链接添加到Github,您可以在其中阅读有关此问题的更多信息,并尝试应用一些测试,以帮助您了解是否受到同一问题的影响 .

    Github link to the pull request and discussion

  • 1

    您需要在ImageDataGenerator中使用preprocessing_function参数 .

    train_datagen = ImageDataGenerator(preprocessing_function=keras.applications.resnet50.preprocess_input)
    

    这将确保您的图像按照您预先训练好的网络的预期进行预处理 .

  • 0

    你有解决问题的方法吗?如果没有,那么这可能是您的resnet中批量规范层的问题 . 我也遇到了类似的问题,因为在训练和测试过程中,keras批量规范层的表现非常不同 . 所以你可以通过以下方式冻结所有bn层:

    BatchNorm()(training=False)

    然后尝试在同一数据集上再次重新训练您的网络 . 还有一件事你应该记住,在训练期间,你应该将训练标志设置为

    import keras.backend as K K.set_learning_phase(1)

    并且在测试期间将此标志设置为0.我认为应该进行上述更改后的工作 .

    如果您已找到问题的任何其他解决方案,请在此处发布,以便其他人可以从中受益 .

    谢谢 .

  • 0

    问题是每个类的数据集太小 . 100k示例/ 1000个类=每个类约100个示例 . 这个数量太少了 . 您的网络可以记住权重矩阵中的所有示例,但为了概括,您应该有更多示例 . 尝试只使用最常见的类,并弄清楚发生了什么 .

  • 1

    根据斯坦福大学,这里有关于微调和转学的一些解释

    • 非常不同的数据集和来自图像网络数据集的非常少的数据集 - 尝试来自不同阶段的线性分类器

    总结一下

    由于数据集非常小,您可能希望从早期图层中提取特征并在其上训练分类器并检查问题是否仍然存在 .

相关问题