问题的总结,在tensorflow中是否支持这种切片然后赋值?
out[tf_a2[y],x[:,None]] = tf_a1[tf_a2[y],x[:,None]]
final = out[:-1]
举个例子,我有一个这样的张量:
tf_a1 = tf.Variable([ [9.968594, 8.655439, 0., 0. ],
[0., 8.3356, 0., 8.8974 ],
[0., 0., 6.103182, 7.330564 ],
[6.609862, 0., 3.0614321, 0. ],
[9.497023, 0., 3.8914037, 0. ],
[0., 8.457685, 8.602337, 0. ],
[0., 0., 5.826657, 8.283971 ],
[0., 0., 0., 0. ]])
我有一个:
tf_a2 = tf.constant([[1, 2, 5],
[1, 4, 6],
[0, 7, 7],
[2, 3, 6],
[2, 4, 7]])
现在,我想将元素(它们的索引)的n个(这里n为2)的组合的值tf_a1
保留在tf_a2
中。什么意思?
例如,在tf_a1
的第一列中,具有值的索引为:(0,3,4)。 tf_a2
中是否有包含以下两个索引的任意组合的行:(0,3),(0,4)或(3,4)。实际上,没有这样的行。因此该列中的所有元素都变为零。
tf_a1
中第二列的索引为(0,1)(0,5)(1,5)。如您所见,记录(1,5)在第一行的tf_a2
中可用。这就是为什么我们将这些保留在tf_a1
中的原因。
这是正确的numpy代码:
y,x = np.where(np.count_nonzero(a1p[a2], axis=1) >= n)
out = np.zeros_like(tf_a1)
out[tf_a2[y],x[:,None]] = tf_a1[tf_a2[y],x[:,None]]
final = out[:-1]
这是此numpy代码的预期输出(但我在tensorflow中需要此输出):
[[0. 0. 0. 0. ]
[0. 8.3356 0. 8.8974 ]
[0. 0. 6.103182 7.330564 ]
[0. 0. 3.0614321 0. ]
[0. 0. 3.8914037 0. ]
[0. 8.457685 8.602337 0. ]
[0. 0. 5.826657 8.283971 ]]
tensorflow代码应该是这样的:
y, x = tf.where(tf.count_nonzero(tf.gather(tf_a1, tf_a2, axis=0), axis=1) >= n)
out = tf.zeros_like(tf_a1)
out[tf_a2[y],x[:,None]] = tf_a1[tf_a2[y],x[:,None]]
final = out[:-1]
这部分代码tf.gather(tf_a1, tf_a2, axis=0), axis=1)
的工作就像切成tf_a1[tf_a2]
更新1
唯一行无效的行:
out[tf_a2[y],x[:,None]] = tf_a1[tf_a2[y],x[:,None]]
final = out[:-1]
任何想法我怎么能在tensorflow中做到这一点,张量对象中是否完全支持这种切片?
感谢您的帮助:)