【发布时间】:2019-05-07 01:17:57
【问题描述】:
我想在 TensorFlow 中做类似这段 Numpy 代码的事情:
a = np.zeros([5, 2])
idx = np.random.randint(0, 2, (5,))
row_idx = np.arange(5)
a[row_idx, idx] = row_idx
意思是用另一个张量索引一个二维张量的所有行,然后为其分配一个张量。我对如何实现这一目标一无所知。
到目前为止,我在 Tensorflow 中可以做的事情如下
a = tf.Variable(tf.zeros((5, 2)))
idx = tf.constant([0, 1, 1, 0, 1])
row_idx = tf.range(5)
indices = tf.transpose([row_idx, idx])
r = tf.gather_nd(a, indices)
tf.assign(r, row_idx) # This line does not work
当我尝试执行此操作时,我在最后一行收到以下错误:
AttributeError: 'Tensor' object has no attribute 'assign'
有没有办法解决这个问题?必须有一些很好的方法来做到这一点,我不想用 for 循环遍历数据并在每个元素的基础上手动分配它。我知道现在数组索引不如 Numpy 的功能先进,但这应该仍然可以通过某种方式实现。
【问题讨论】:
标签: python tensorflow