根据另一个张量的索引创建新的张量并分配它的值

Create new tensor based on indexes from another tensor and allocate with it's values

我有一个张量 t 看起来像这样 [[0, 1, 1.5], [1, 1, 7.3], [2, 0, 2.3]] 我需要创建形状为 (3, 3, 1) 的新张量 t1 其中 t1[t[:, :1], t[:, 1:2]](来自第一列的元素用作第一坐标,来自第二列的元素用作第二坐标)分配给来自 t 第三列的元素。像这样t1 = [[[0.0], [1.5], [0.0]], [[0.0], [7.3], [0.0]], [[2.3], [0.0], [0.0]]]。如何在没有循环的情况下使用 TensorFlow(或 Numpy)中的矩阵运算来做到这一点?

你可以使用 tf.sparse_to_dense

tf.sparse_to_dense(tf.to_int32(t[:, :2]), [3, 3], t[:, 2])[..., None]

怎么样:

import numpy as np

t = np.asarray([[0,1,1.5],[1,1,7.3],[2,0,2.3]])

t1 = np.zeros([3,3,1])
t1[t[:,0].astype(int), t[:,1].astype(int),0] = t[:,2]