Tensorflow 如何在二维张量的第二维上使用张量流散射?
TL;DR:如何将每个实例有2个标签的2D二进制张量拆分为每个实例只有1个标签的2个张量,如下图所示: 作为自定义丢失函数的一部分,我尝试将多标签y张量(每个实例有2个标签)拆分为2个y张量(每个实例有1个标签)。 当我在1D y张量上进行此操作时,此代码非常有效:Tensorflow 如何在二维张量的第二维上使用张量流散射?,tensorflow,machine-learning,keras,deep-learning,Tensorflow,Machine Learning,Keras,Deep Learning,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 =
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
(索引)不正确,的形状也不替换(更新)。
据我所知,tf.scatter\u nd
只能更新变量的第一个维度,因此我如何才能绕过它?我怎样才能得到所需的索引呢?我觉得你走的是一条迂回的道路。这是我的解决办法。感觉它比你尝试使用的更直接(TF1.14)
因此,我们的想法是为每行获取前2个标签的索引。然后使用tf.split
将其拆分为两列。然后使用one_hot
将这些索引转换回onehot向量
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]))