我有一对张力器 S
和 T
的尺寸 (s1,...,sm)
和 (t1,...,tn)
与 si < ti
. 我想在每一个维度中指定一个索引列表。T
以 "嵌入" S
在 T
. 如果 I1
是一系列的 s1
指数中 (0,1,...,t1)
同样 I2
以至于 In
我想做这样的事情 T.select(I1,...,In)=S
这样一来 T
的条目等于 S
在指数上 (I1,...,In)
.例如
`S=
[[1,1],
[1,1]]
T=
[[0,0,0],
[0,0,0],
[0,0,0]]
T.select([0,2],[0,2])=S
T=
[[1,0,1],
[0,0,0],
[1,0,1]]`
如果你能灵活地使用NumPy 只针对指数部分那么,这里有一个方法,通过使用以下方法构建一个开放的网格 numpy.ix_()
并使用这个网格来填充张量的值。S
. 如果不能接受,那么你可以使用 torch.meshgrid()
下面是两种方法的说明,并在注释中穿插说明。
# input tensors to work with
In [174]: T
Out[174]:
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
# I'm using unique tensor just for clarity; But any tensor should work.
In [175]: S
Out[175]:
tensor([[10, 11],
[12, 13]])
# indices where we want the values from `S` to be filled in, along both dimensions
In [176]: idxs = [[0,2], [0,2]]
现在我们将利用 np.ix_()
或 torch.meshgrid()
通过传递指数来生成一个开放的网格。
# mesh using `np.ix_`
In [177]: mesh = np.ix_(*idxs)
# as an alternative, we can use `torch.meshgrid()`
In [191]: mesh = torch.meshgrid([torch.tensor(lst) for lst in idxs])
# replace the values from tensor `S` using basic indexing
In [178]: T[mesh] = S
# sanity check!
In [179]: T
Out[179]:
tensor([[10, 0, 11],
[ 0, 0, 0],
[12, 0, 13]])