如何为Keras计算Pandas DataFrame的类别权重?

6

我正在尝试

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])

我不明白你在这里所说的类别权重是什么意思? - Mohit Motwani
@MohitMotwani 我更新了问题以解释。 - Shamoon
你可以参考这个问题的链接 https://dev59.com/c1cQ5IYBdhLWcg3wA_FA - giser_yugang
1
@giser_yugang 对于我特定的 pandas 问题没有帮助。 - Shamoon
2个回答

6
只需将独热编码转换为分类标签即可:
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))

3
创建至少包含每个类别一个示例的样本数据。
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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接