tf.one_hot没有渐变

问题描述 投票:1回答:1

我正在尝试创建一个自定义丢失函数,它具有一个整数的输出(在loss函数中转换为一个热编码)。

但问题是one_hot没有可微分的渐变。有没有解决方法?

def new_loss(hidden, output, random_size=20):

    output1 = tf.cast(
        output,
        dtype=tf.int32,
    )
    one_hot = tf.one_hot(output1, num_words, dtype=tf.int32,)

    one_hot = tf.cast(
        one_hot,
        dtype=tf.float32
    )

    score = K.dot(hidden, one_hot)
    random_words = tf.random.uniform((random_size,), maxval=num_words, dtype=tf.dtypes.int32)
    random_words_1_hot = tf.one_hot(random_words, num_words, dtype=tf.float32)
    scores = K.dot(random_words_1_hot, hidden)
    average = K.sum(K.log (1 - K.sigmoid(scores)) / random_size)

    return (-1 * K.log (K.sigmoid(score)) - average)
ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.
python tensorflow keras
1个回答
0
投票

问题不在于one_hot编码本身,而是在一系列强制转换操作中。更具体地说,TensorFlow不会通过整数传播。假设hiddenoutput都是float类型,如果你改变它

output1 = tf.cast(output, dtype=tf.int32,)
one_hot = tf.one_hot(output1, num_words, dtype=tf.int32,)

one_hot = tf.cast(one_hot, dtype=tf.float32)

对此

one_hot = tf.one_hot(tf.cast(output, tf.int32), num_words, dtype=tf.float32)

你会得到你的渐变。

更详细的例子:

one_hot1 = tf.one_hot(tf.cast(np.random.rand(2), tf.int32), num_words, dtype=tf.float32)
hidden = tf.constant([1.,2.,3.,4.], shape=(2,2))

one_hot = tf.cast(one_hot1, dtype=tf.float32)

hidden1 = tf.cast(hid, tf.float32)
score = tf.matmul(hidden, one_hot)
random_words = tf.random.uniform((random_size,), maxval=num_words, dtype=tf.float32)
random_words_1_hot = tf.one_hot(tf.cast(random_words, tf.int32), num_words, dtype=tf.float32)
scores = tf.matmul(random_words_1_hot, hidden)
average = tf.reduce_sum(tf.log(1 - tf.sigmoid(scores)) / random_size)

res = -1 * tf.log(tf.sigmoid(score)) - average
grads = tf.gradients(res, [hidden1, one_hot1])
sess = tf.Session()
print(sess.run(res))
print(sess.run(grads))

为了保持一致性,我使用了核心TF操作。你可以看到,如果one_hot1最初将被创建为tf.int,然后重铸到float,那么就没有渐变。更多关于这里https://github.com/tensorflow/tensorflow/issues/20524

© www.soinside.com 2019 - 2024. All rights reserved.