Keras 中的自定义损失与 softmax 到 one-hot

2023-12-24

我有一个输出 Softmax 的模型,我想开发一个自定义损失函数。期望的行为是:

1)Softmax 为 one-hot (通常我会执行 numpy.argmax(softmax_vector) 并将空向量中的索引设置为 1,但这在损失函数中是不允许的)。

2) 将得到的 one-hot 向量乘以我的嵌入矩阵以获得嵌入向量(在我的上下文中:与给定单词相关联的单词向量,其中单词已被标记并分配给索引或 Softmax 的类)输出)。

3) 将此向量与目标进行比较(这可能是正常的 Keras 损失函数)。

我通常知道如何编写自定义损失函数,但不知道如何执行此操作。我找到了这个密切相关的问题 https://stackoverflow.com/questions/50082781/how-to-produce-a-one-hot-output-in-keras(未答复),但我的情况有点不同,因为我想保留我的 softmax 输出。


可以在客户损失函数中混合使用 TensorFlow 和 keras。一旦你可以访问所有 Tensorflow 功能,事情就变得非常容易。我只是给你一个例子来说明如何实现这个功能。

import tensorflow as tf
def custom_loss(target, softmax):
    max_indices = tf.argmax(softmax, -1)

    # Get the embedding matrix. In Tensorflow, this can be directly done
    # with tf.nn.embedding_lookup
    embedding_vectors = tf.nn.embedding_lookup(you_embedding_matrix, max_indices)

    # Do anything you want with normal keras loss function
    loss = some_keras_loss_function(target, embedding_vectors)

    loss = tf.reduce_mean(loss)
    return loss
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Keras 中的自定义损失与 softmax 到 one-hot 的相关文章

随机推荐