【问题标题】:Customize ImageDataGenerator for stratified sampling on Multi-Labels自定义 ImageDataGenerator 以在多标签上进行分层抽样
【发布时间】:2022-01-04 13:12:25
【问题描述】:

我正在处理multi-label classification 问题,我的large-scale 数据高度imbalanced。所以,我需要应用stratified sampling,直觉是我的ImageDataGeneratorevery batch 中按比例从each class 中采样数据。任何建议/解决方案都将受到高度赞赏。

【问题讨论】:

    标签: python tensorflow keras deep-learning


    【解决方案1】:

    确实是个好问题。

    据我所知,ImageDataGenerator() 中没有内置的多标签分层。

    我将建议两种可能的方法:

    1. 您可以将Sequence() 类子类化,以便能够准确控制您在网络中的每一步提供的内容。您可以覆盖__getitem__() 方法,并确保在每批中按比例采样数据。

    2. 您可以使用外部库,在将数据输入网络之前对其进行预处理。通过这种方式,您可以预处理数据并使用tf.data.Dataset() 管道将数据提供给您的网络。

    (2)的一个例子是这个:

    from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
    import numpy as np
    
    X = np.array([[1,2], [3,4], [1,2], [3,4], [1,2], [3,4], [1,2], [3,4]])
    y = np.array([[0,0], [0,0], [0,1], [0,1], [1,1], [1,1], [1,0], [1,0]])
    
    mskf = MultilabelStratifiedKFold(n_splits=2, shuffle=True, random_state=0)
    
    for train_index, test_index in mskf.split(X, y):
       print("TRAIN:", train_index, "TEST:", test_index)
       X_train, X_test = X[train_index], X[test_index]
       y_train, y_test = y[train_index], y[test_index]
    

    【讨论】:

    • 我选择了选项 1 并创建了一个自定义批次,其中每个类别的样本按比例添加。但是,我的批次有时不完整,例如我给了 batch_size 32 并从 3 个类中的每一个中选择了 10 个样本,总共 30 个(比 batch_size 少 2 个)。那么,用最后 2 个条目填充批次的最佳方法是什么?它应该是随机的还是有其他更好的方法?
    • 是的,它可能是随机的,如果你的 batch_size 不能被类数整除,实际上这是不可能的,不可能完美地平衡它。
    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 2022-10-13
    相关资源
    最近更新 更多