【问题标题】:Tensorflow 2.0 (Keras) classification with restricted classes具有受限类的 Tensorflow 2.0 (Keras) 分类
【发布时间】:2020-09-17 12:20:05
【问题描述】:

问题背景

我有一个基本的分类问题,将每一行分为 20 个类别之一。

但是,有一个转折点。对于每一行,这 20 个类中只有一些是有效的 - 这是预先知道的。

在 tensorflow 1.0 中,我一直在取消不可能类的 logits。唯一的修改是损失函数:

def getLoss(logits, y, restrictions):
    logits = tf.where(restrictions, -1000.0 * tf.ones_like(y), logits)
    return tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y)

loss = getLoss(logits, y, restrictions)
trainer = tf.train.RMSPropOptimizer(learnRate).minimize(loss)

问题

我有一个适用于 Tensorflow 1.0 的解决方案,它是对损失函数的简单修改。但是,我想在 Tensorflow 2.0 和 Keras 中重写它。

我假设我需要将类限制矩阵与输入一起传递给model.fit()。我该怎么做呢?

次优解决思路

一个简单的解决方案(也是 Frederik 提出的)是将输入和类限制矩阵连接起来,让神经网络从头开始学习类限制的概念。

但是,这并不可靠,并且会使神经网络不必要地变大。 Keras 有没有更好、更简单的方法?

【问题讨论】:

  • 你能扩展那个“类限制”吗?
  • @RokKralj 如果范围是在 TF2 中重写...有没有办法在 TF1 中对代码进行演示实现?
  • 添加了 TF1 代码示例。

标签: python tensorflow keras tensorflow2.0 tf.keras


【解决方案1】:

您的损失函数可以完全以相同的方式实现:

def getLoss(logits, y, restrictions):
    logits = tf.where(restrictions, -1000.0 * tf.ones_like(y, dtype=tf.float32), logits)
    return tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)

然后可以将模型定义如下:

x_input = Input(shape=(100,))
y_true = Input(shape=(20,))
restrictions = Input(shape=(20,), dtype=tf.bool)
# ... model definition here
y_pred = Dense(20)(x_input)
model = Model([x_input, restrictions, y_true], y_pred)

要编译模型,添加损失如下:

model.add_loss(getLoss(y_pred, y_true, restrictions))
model.compile(optimizer='rmsprop')

最后,可以使用模型的fit方法训练模型。例如:

x = np.random.random((1000, 100))
restrictions = np.random.binomial(1, p=0.5, size=(1000, 20))
y = np.random.randint(20, size=1000)
y_onehot = np.eye(20)[y]
model.fit((x, restrictions, y_onehot), epochs=10, batch_size=10)

【讨论】:

  • 我认为在推理时这个解决方案不会产生准确的结果......掩码只涉及损失计算......对输出概率没有任何约束 > 0 和不等于 0,如在输入掩码中
  • OP 专门询问损失函数。在推理时应用限制是微不足道的。
  • 能否请您详细说明如何在推理时应用限制?
【解决方案2】:

这在推理时是如何工作的?你知道推理时新行的类限制吗?

如果答案是“是”:

我认为您不应该将整个类限制矩阵作为输入,而应该使用串联的类限制向量。因此,不要用形状(n,) 喂row,而是用形状(n+20,) 喂row_plus_class_restrictions。

row_feature_0
row_feature_1
...
row_feature_n
0
1
.
.
.
1

这样您也不需要消除任何错误,模型将根据分类损失了解它应该输出的内容。

如果答案是“否”:

那么你的模型没有多大意义。训练数据是一堆(row, class_restrictions, class_it_should_be),维度为(nb_row_features + 20 + 20),对吗?你想训练什么——真正的实际应用——你的行中有什么样的数据?如果答案是否定的,我不明白你想要什么。

【讨论】:

    【解决方案3】:

    假设你必须在推理时通过类限制矩阵...

    您可以在简单的Lambda 层内手动构建对 logits 的限制操作。然后你在受限的 logits 上应用 softmax 并应用标准的交叉熵损失函数。

    这是一个虚拟示例,其中我们以二进制格式对类进行掩码/限制。

    n_class = 8
    n_sample = 10
    X = np.random.uniform(0,1, (n_sample,30))
    y = np.random.randint(0,n_class, (n_sample,))
    mask = np.random.randint(0,2, (n_sample,n_class))
    
    def mask_logits(logits, mask):
        restrictions = (mask > 0)
        return tf.keras.backend.switch(restrictions, -1000.0 * tf.ones_like(logits), logits)
    
    inp_x = Input((X.shape[-1],))
    inp_mask = Input((n_class,))
    logits = Dense(n_class)(inp_x)
    out = Lambda(mask_logits)(logits, inp_mask)
    out = Activation('softmax')(out)
    model = Model([inp_x, inp_mask], out)
    model.compile('adam', 'sparse_categorical_crossentropy')
    
    model.fit([X,mask], y, epochs=3)
    

    在推理时可以通过这种方式检索预测:

    pred = model.predict([X, mask])
    

    最后,我们计算一些简单的检查:

    >>> pred.sum(1)
    array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], dtype=float32)
    

    预测概率之和为 1 行

    >>> pred == 0
    array([[ True,  True, False,  True, False, False,  True, False],
           [ True,  True,  True,  True, False, False,  True,  True],
           [False, False, False,  True, False, False,  True,  True],
           [False, False,  True, False, False,  True,  True, False],
           [False, False,  True, False, False,  True,  True, False],
           [False, False,  True,  True, False, False, False, False],
           [False,  True, False,  True, False, False,  True,  True],
           [ True, False, False, False, False,  True, False,  True],
           [False,  True,  True, False, False, False,  True, False],
           [False,  True,  True, False,  True, False, False, False]])
    

    我们的二进制掩码指定的一些预测概率等于 0

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2019-08-30
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2021-11-30
      相关资源
      最近更新 更多