我有一个二维张量 A,我希望将其非零条目替换为另一个张量 B,如下所示。
A = tf.constant([[1.0,0,1.0],[0,1.0,0],[1.0,0,1.0]],dtype=tf.float32)
B = tf.constant([1.0,2.0,3.0,4,0,5.0],dtype=tf.float32)
所以我希望最终的 A 为
A = tf.constant([[1.0,0.0,2.0],[0,3.0,0.0],[4.0,0.0,5.0]],dtype=tf.float32)
我得到 A 的非零元素的索引如下
where_nonzero = tf.not_equal(A, tf.constant(0, dtype=tf.float32))
indices = tf.where(where_nonzero)
indices = <tf.Tensor: shape=(5, 2), dtype=int64, numpy=
array([[0, 0],
[0, 2],
[1, 1],
[2, 0],
[2, 2]])>
有人可以帮忙吗?
最佳答案
IIUC,您应该能够使用tf.tensor_scatter_nd_update
:
import tensorflow as tf
A = tf.constant([[1.0,0,1.0],[0,1.0,0],[1.0,0,1.0]],dtype=tf.float32)
B = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0],dtype=tf.float32)
where_nonzero = tf.not_equal(A, tf.constant(0, dtype=tf.float32))
indices = tf.where(where_nonzero)
A = tf.tensor_scatter_nd_update(A, indices, B)
print(A)
tf.Tensor(
[[1. 0. 2.]
[0. 3. 0.]
[4. 0. 5.]], shape=(3, 3), dtype=float32)
关于python - 使用 Tensorflow 中的索引为 2D 张量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71222431/