sklearn utils 大型数据集的compute_class_weight 函数

问题描述 投票:0回答:2

我正在 postgres 数据库中基于大约 20+ GB 基于文本的分类数据训练张量流 keras 顺序模型,我需要为模型赋予类别权重。 这就是我正在做的事情。

class_weights = sklearn.utils.class_weight.compute_class_weight('balanced', classes, y)

model.fit(x, y, epochs=100, batch_size=32, class_weight=class_weights, validation_split=0.2, callbacks=[early_stopping])

由于我无法将整个内容加载到内存中,我想我可以在 keras 模型中使用 fit_generator 方法。

但是我如何根据这些数据计算类别权重sklearn 没有为此提供任何特殊功能,它是合适的工具吗

我想过对多个随机样本进行此操作,但是有没有更好的方法可以使用整个数据

python tensorflow machine-learning scikit-learn data-science
2个回答
5
投票

您可以使用生成器,也可以计算类别权重。

假设您有这样的发电机

train_generator = train_datagen.flow_from_directory(
        'train_directory',
        target_size=(224, 224),
        batch_size=32,
        class_mode = "categorical"
        )

训练集的类别权重可以这样计算

class_weights = class_weight.compute_class_weight(
           'balanced',
            np.unique(train_generator.classes), 
            train_generator.classes)

[编辑1] 既然你在评论中提到了 postgres sql,我在这里添加原型答案。

首先使用 postgres sql 中的单独查询获取每个类的计数,并用它来计算类权重。你可以手动计算它。基本逻辑是权重最小的类别的计数值为 1,其余类别的值为 <1 based on the relative count to the least weighed class.

例如,您有 3 个类别 A、B、C,值为 100,200,150,则类别权重变为 {A:1,B:0.5,C:0.66}

从 postgres sql 获取值后手动计算它。

[查询]

cur.execute("SELECT class, count(*) FROM table group by classes order by 1")
rows = cur.fetchall()

上面的查询将返回包含从最小到最高排序的元组(类名称、每个类的计数)的行。

然后下面的代码将创建类权重字典

class_weights = {}
for row in rows:
    class_weights[row[0]]=rows[0][1]/row[1] 
    #dividing the least value the current value to get the weight, 
    # so that the least value becomes 1, 
    # and other values becomes < 1

1
投票

Sklearn 不用于这样的大型处理。理想情况下,我们必须自己实现它,特别是当它是您定期运行的管道的一部分时。

© www.soinside.com 2019 - 2024. All rights reserved.