【问题标题】:How to calculate class weights of a Pandas DataFrame for Keras?如何为 Keras 计算 Pandas DataFrame 的类权重?
【发布时间】:2019-07-17 10:22:30
【问题描述】:

我在努力

print(Y)
print(Y.shape)

class_weights = compute_class_weight('balanced',
                                     np.unique(Y),
                                     Y)
print(class_weights)

但这给了我一个错误:

ValueError: classes should include all valid labels that can be in y

我的Y 看起来像:

       0  1  2  3  4
0      0  0  1  0  0
1      1  0  0  0  0
2      0  0  0  1  0
3      0  0  1  0  0
...
14992     0  0  1  0  0
14993      0  0  1  0  0

我的Y.shape 看起来像: (14993, 5)

在我的keras 模型中,我想使用class_weights,因为它分布不均:

model.fit(X, Y, epochs=100, shuffle=True, batch_size=1500, class_weights=class_weights, validation_split=0.05, verbose=1, callbacks=[csvLogger])

【问题讨论】:

  • 我不明白你这里所说的类 wieghts 是什么意思?
  • @MohitMotwani 我更新了问题来解释
  • 你可以参考这个问题stackoverflow.com/questions/43481490/…
  • @giser_yugang 对我的pandas 问题没有帮助

标签: python pandas keras


【解决方案1】:

创建一些示例数据,每个类至少有一个示例

df = pd.DataFrame({
    '0': [0, 1, 0, 0, 0, 0],
    '1': [0, 0, 0, 0, 1, 0], 
    '2': [1, 0, 0, 1, 0, 0],
    '3': [0, 0, 1, 0, 0, 0],
    '4': [0, 0, 0, 0, 0, 1],
})

堆叠列(从宽表转换为长表)

df = df.stack().reset_index()
>>> df.head()

  level_0   level_1     0
0   0       0       0
1   0       1       0
2   0       2       1
3   0       3       0
4   0       4       0

获取每个数据点的类

Y = df[df[0] == 1]['level_1']
>>> Y
2     2
5     0
13    3
17    2
21    1
29    4

计算类权重

class_weights = compute_class_weight(
    'balanced', np.unique(Y), Y
)
>>> print(class_weights)
[1.2 1.2 0.6 1.2 1.2]

【讨论】:

    【解决方案2】:

    只需将 one-hot 编码转换为分类标签:

    from sklearn.utils import class_weight
    
    y = Y.idxmax(axis=1)
    
    class_weights = class_weight.compute_class_weight('balanced',
                                                      np.unique(y),
                                                      y)
    
    # Convert class_weights to a dictionary to pass it to class_weight in model.fit
    class_weights = dict(enumerate(class_weights))
    

    【讨论】:

      猜你喜欢
      • 2021-08-05
      • 1970-01-01
      • 2017-12-28
      • 2016-04-04
      • 2017-10-08
      • 2019-08-01
      • 2017-12-15
      • 2022-01-18
      相关资源
      最近更新 更多