如何为Keras计算Pandas DataFrame的类权重? [英] How to calculate class weights of a Pandas DataFrame for Keras?
本文介绍了如何为Keras计算Pandas DataFrame的类权重?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试
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
,因为它是不均匀的分布:
In my keras
model, I want to use the class_weights
as it is an uneven distribution:
model.fit(X, Y, epochs=100, shuffle=True, batch_size=1500, class_weights=class_weights, validation_split=0.05, verbose=1, callbacks=[csvLogger])
推荐答案
创建一些示例数据,每个类至少包含一个示例
Create some sample data with at least one example per class
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],
})
堆叠列(从宽表转换为长表)
Stack the columns (convert from wide to long table)
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]
这篇关于如何为Keras计算Pandas DataFrame的类权重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文