【问题标题】:Keras class_weight in multi-label binary classification多标签二元分类中的 Keras class_weight
【发布时间】:2018-06-23 14:27:31
【问题描述】:

在使用 class_weight 解决我的多标签问题时遇到问题。即每个标签不是0就是1,但是每个输入样本有很多标签。

代码(用于 MWE 的随机数据):

import tensorflow as tf
from keras.models import Sequential, Model
from keras.layers import Input, Concatenate, LSTM, Dense
from keras import optimizers
from keras.utils import to_categorical
from keras import backend as K
import numpy as np

# from http://www.deepideas.net/unbalanced-classes-machine-learning/
def sensitivity(y_true, y_pred):
        true_positives = tf.reduce_sum(tf.round(K.clip(y_true * y_pred, 0, 1)))
        possible_positives = tf.reduce_sum(tf.round(K.clip(y_true, 0, 1)))
        return true_positives / (possible_positives + K.epsilon())

# from http://www.deepideas.net/unbalanced-classes-machine-learning/    
def specificity(y_true, y_pred):
        true_negatives = tf.reduce_sum(K.round(K.clip((1-y_true) * (1-y_pred), 0, 1)))
        possible_negatives = tf.reduce_sum(K.round(K.clip(1-y_true, 0, 1)))
        return true_negatives / (possible_negatives + K.epsilon())

def to_train(a_train, y_train):
        hours_np = [np.arange(a_train.shape[1])]*a_train.shape[0]
        train_hours = to_categorical(hours_np)
        n_samples = a_train.shape[0]
        n_classes = 4
        features_in = np.zeros((n_samples, n_classes))
        supp_feat = np.random.choice(n_classes, n_samples)
        features_in[np.arange(n_samples), supp_feat] = 1

        #This model has 3 separate inputs
        seq_model_in = Input(shape=(1,),batch_shape=(1, 1, a_train.shape[2]), name='seq_model_in')
        feat_in = Input(shape=(1,), batch_shape=(1, features_in.shape[1]), name='feat_in')
        feat_dense = Dense(1)(feat_in)
        hours_in = Input(shape=(1,), batch_shape=(1, 1, train_hours.shape[2]), name='hours_in')

        #Model intermediate layers
        t_concat = Concatenate(axis=-1)([seq_model_in, hours_in])
        lstm_layer = LSTM(1, batch_input_shape=(1, 1, (a_train.shape[2]+train_hours.shape[2])), return_sequences=False, stateful=True)(t_concat)
        merged_after_lstm = Concatenate(axis=-1)([lstm_layer, feat_dense]) #may need another Dense() after
        dense_merged = Dense(a_train.shape[2], activation="sigmoid")(merged_after_lstm)

        #Define input and output to create model, and compile
        model = Model(inputs=[seq_model_in, feat_in, hours_in], outputs=dense_merged)
        model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[sensitivity, specificity])

        class_weights = {0.:1., 1.:118.}
        seq_length = 23

        #TRAINING (based on http://philipperemy.github.io/keras-stateful-lstm/)
        for epoch in range(2):
            for i in range(a_train.shape[0]):
                    y_true_1 = np.expand_dims(y_train[i,:], axis=1)
                    y_true = np.swapaxes(y_true_1, 0, 1)
                    #print 'y_true', y_true.shape
                    for j in range(seq_length-1):
                            input_1 = np.expand_dims(np.expand_dims(a_train[i][j], axis=1), axis=1)
                            input_1 = np.reshape(input_1, (1, 1, a_train.shape[2]))
                            input_2 = np.expand_dims(np.array(features_in[i]), axis=1)
                            input_2 = np.swapaxes(input_2, 0, 1)
                            input_3 = np.expand_dims(np.array([train_hours[i][j]]), axis=1)
                            tr_loss, tr_sens, tr_spec = model.train_on_batch([input_1, input_2, input_3], y_true, class_weight=class_weights)
                    model.reset_states()
       return 0

a_train = np.random.normal(size=(50,24,5625))
y_train = a_train[:, -1, :]
a_train = a_train[:, :-1, :]
y_train[y_train > 0.] = 1.
y_train[y_train < 0.] = 0.
to_train(a_train, y_train)

我得到的错误是:

ValueError: `class_weight` must contain all classes in the data. The classes set([330]) exist in the data but not in `class_weight`.

'set([...])' 中的值在每次运行时都会发生变化。但正如我所说,数据中仅有的两个类是 0 和 1;每个样本只有多个标签。例如,一个响应 (y_train) 如下所示:

print y_train[0,:]
#[ 0.  0.  1. ...,  0.  1.  0.]

如何使用class_weights 解决 Keras 中的多标签问题?

【问题讨论】:

    标签: tensorflow machine-learning keras classification multilabel-classification


    【解决方案1】:

    是的。这是 keras 中的一个已知错误 (issue #8011)。基本上,keras 代码在确定类数时采用 one-hot 编码,而不是多标签序数编码。

    keras/engine/training.py:

    # if 2nd dimension is greater than 1, it must be one-hot encoded, 
    # so let's just get the max index...
    if y.shape[1] > 1:
      y_classes = y.argmax(axis=1)
    

    我现在想不出更好的解决方法,除了设置y_true[:, 1] = 1,即“保留”y 中的1 位置始终为一个。这将导致y_classes = 1(这是二进制分类中的正确值)。

    为什么会起作用?y_true[i] 获得像[0, 0, ..., 0, 1, ...] 这样带有一些前导零的值时,代码会失败。 Keras 实现(错误地)通过最大元素的索引来估计类的数量,结果是一些j &gt; 1,其中y[i][j] = 1。这使得 Keras 引擎认为有超过 2 个类,所以提供的 class_weights 是错误的。设置y_true[i][1] = 1 确保j &lt;= 1(因为np.argmax 选择最小的最大索引),这允许绕过keras 守卫。

    【讨论】:

    • 感谢您的提示,马克西姆。我看了你链接到的代码,我有点困惑。为什么您的解决方案有效?你能把它合并到我提供的代码中吗?
    • 谢谢,我做到了。我想知道您是否可以在答案中提供更多解释?那我就可以接受了。我认为这对未来的读者会有用。
    • 当然。更新了我的答案
    • 它可以绕过错误信息,但你不是说第一个真正的标签是1吗?这可能会破坏其他东西,对吧?
    • 这就是我使用“保留”一词的原因。在 0 和 1 处向您的 y 添加两个人工类,然后训练其余部分
    【解决方案2】:

    您可以创建一个回调,将标签的索引附加到列表中 例如:

    y = [[0,1,0,1,1],[0,1,1,0,0]]

    将创建一个列表:category_list = [1, 3, 4, 1, 2]

    标签的每个实例都记录在 category_list 中

    那么你可以使用

    weighted_list = class_weight.compute_class_weight('balanced', np.unique(category_list), category_list)

    然后只需将 weighted_list 转换为字典以在 Keras 中使用。

    【讨论】:

    • 您好,感谢您的回答。我还不太明白,但我很欣赏这个想法。我猜y 这里是两个多标签响应,就像我有的一样,但是你为什么需要 np.unique?为什么之后需要将category_list 转换为字典?
    • 如果你使用 Keras,它需要一个字典来记录你的权重
    • 完成这个:我认为你需要 np.unique() 因为字典需要唯一的键。
    【解决方案3】:

    对于多标签,我发现了两个选项:

    1. 创建多输出模型,每 1 个标签 1 个输出并通过标准 class_weight 字典
    2. 创建 weights_aware_binary_crossentropy 损失,它可以根据传递的 class_weight 字典列表和 y_true 计算掩码并执行:

    K.binary_crossentropy(y_true, y_pred) * mask

    【讨论】:

      猜你喜欢
      • 2019-07-14
      • 2018-08-04
      • 2019-02-26
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 2019-01-06
      相关资源
      最近更新 更多