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

时间:2019-02-23 13:21:13

标签: python pandas keras

我正在尝试

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

2 个答案:

答案 0 :(得分:3)

只需将一键编码转换为分类标签:

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

答案 1 :(得分:2)

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

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]