【发布时间】: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