【问题标题】:How can I use Tensorflows scatter_nd on the second dimension of a 2D tensor?如何在二维张量的第二维上使用 Tensorflows scatter_nd?
【发布时间】:2019-10-05 13:21:09
【问题描述】:

TL;DR:如何将每个实例 2 个标签的 2D 二进制张量拆分为每个实例只有 1 个标签的 2 个张量,如下图所示:

作为自定义损失函数的一部分,我试图将一个多标签 y 张量(每个实例有 2 个标签)拆分为 2 个 y 张量,每个实例有 1 个标签。 当我在 1D y 张量上执行此操作时,此代码效果很好:

y_true = tf.constant([1., 0., 0., 0., 1., 0., 0., 0., 0.])
label_cls = tf.where(tf.equal(y_true, 1.))
idx1, idx2 = tf.split(label_cls,2)
raplace = tf.constant([1.])
y_true_1 = tf.scatter_nd(tf.cast(idx1, dtype=tf.int32), raplace, [tf.size(y_true)]) 
y_true_2 = tf.scatter_nd(tf.cast(idx2, dtype=tf.int32), raplace, [tf.size(y_true)])  

with tf.Session() as sess:
    print(sess.run([y_true_1,y_true_2]))

我得到:

[array([1., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32), array([0., 0., 0., 0., 1., 0., 0., 0., 0.], dtype=float32)]

但是当我在训练中使用批处理时,我得到了这个错误:

Invalid argument: Outer dimensions of indices and update must match.

由于我的“y 张量”是 2D 而不是 1D,在这种情况下 - idx1, idx2(索引)不正确,replace(更新)的形状也不正确。 据我了解,tf.scatter_nd 只能更新变量的第一个维度,那么我该如何解决呢?以及如何获得所需的索引?

【问题讨论】:

    标签: tensorflow machine-learning keras deep-learning


    【解决方案1】:

    我觉得你走的是一条曲折的道路。这是我的解决方案。感觉它比您尝试使用的更简单(尝试使用 tf 1.14)。

    import tensorflow as tf
    
    y_true = tf.constant([[1, 0, 1, 0],[0, 1, 1, 0]])
    _, label_inds = tf.math.top_k(y_true, k=2)
    idx1, idx2 = tf.split(label_inds,2, axis=1)
    
    y_true_1 = tf.one_hot(idx1, depth=4)
    y_true_2 = tf.one_hot(idx2, depth=4)
    
    with tf.Session() as sess:
    
        print(sess.run([y_true_1, y_true_2]))
    

    因此,您可以获取每行前 2 个标签的索引。然后使用tf.split 将其拆分为 2 列。然后使用 one_hot 将这些索引转换回 onehot 向量。

    【讨论】:

      猜你喜欢
      • 2017-12-20
      • 2020-09-26
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      相关资源
      最近更新 更多