为多类分类设置偏差 python tensorflow keras

setting bias for multiclass classification python tensorflow keras

附件 model 展示了如何在不平衡 class化问题 initial_bias = np.log([pos/neg]) 的情况下添加偏差。如果你有 multi-class classification with unbalanced data,有没有办法增加偏差,比如 5 classes where classes are have distribution (0.4,0.3,0.2.0.08 and 0.02)

2) 在这种情况下如何计算和使用 class 权重?

更新 1

I found a way to apply weights, still not sure how to use bias

#####adding weights 20 Feb
weight_for_0 = ( 1/ 370)*(370+ 977+ 795)/3
weight_for_1 = ( 1/ 977)*(370+ 977+ 795)/3
weight_for_2 = (1 / 795)*(370+ 977+ 795)/3

#array([0, 1, 2]), array([370, 977, 795])

class_weights_dict = {0: weight_for_0, 1: weight_for_1, 2:weight_for_2}
class_weights_dict
Dcnn.fit(train_dataset,
         epochs=NB_EPOCHS,
         callbacks=[MyCustomCallback()],verbose=2,validation_data=test_dataset, class_weight=class_weights_dict)

考虑到您正在使用 'softmax':

softmax = exp(neurons) / sum(exp(neurons))

并且您希望 类 的结果为:

frequency = [0.4 , 0.3 , 0.2 , 0.08 , 0.02]

偏差应由等式(逐元素)给出:

frequency = exp(biases) / sum(exp(biases))

这形成了一个方程组:

  • f1 = e^b1 / (e^b1 + e^b2 + ... + e^b5)
  • f2 = e^b2 / (e^b1 + e^b2 + ... + e^b5)
  • ...
  • f5 = e^b5 / (e^b1 + e^b2 + ... + e^b5)

如果你能解出这个方程组,你就会得到你想要的偏差。

我使用excel和测试误差法来确定对于你想要的频率,你的偏见应该分别是:

[1.1 , 0.81 , 0.4 , -0.51 , -1.9] 

我真的不知道如何轻松解决该系统,但您可以继续尝试 excel 或其他东西,直到找到解决方案。


向图层添加偏差 - 方法 1。

定义层时使用名称,例如:

self.last_dense = layers.Dense(units=3, activation="softmax", name='last_layer')

您可能需要先构建模型,因此:

dummy_predictions = model.predict(np.zeros((1,) + input_shape))

然后你得到权重:

weights_and_biases = model.get_layer('last_layer').get_weights()
w, b = weights_and_biases
new_biases = np.array([-0.45752, 0.51344, 0.30730])
model.get_layer('last_layer').set_weights([w, new_biases])

方法二

def bias_init(bias_shape):
    return K.variable([-0.45752, 0.51344, 0.30730])

self.last_dense = layers.Dense(units=3, activation="softmax", bias_initializer=bias_init)

除了@Daniel Möller 的回答,求解方程组

  • f1 = e^b1 / (e^b1 + e^b2 + ... + e^b5)

    ...

  • f5 = e^b5 / (e^b1 + e^b2 + ... + e^b5)

您不需要 excel 或任何东西。只需计算 bi = ln(fi).

要计算fi = e^bi / (sum of e^bj),请注意fi/fj = e^(bi-bj)。假设最低频率是fk。您可以设置 bk= 0,然后使用 bi = bj + ln(fi/fj).

计算每隔一个 class 偏差