`unbind()`返回 PyTorch 中张量的视图吗?

问题描述 投票:0回答:1

unbind()

的文档
只是说如下:

返回沿给定维度的所有切片的元组,已经没有它了。

那么,这是否意味着

unbind()
返回张量的视图(元组)而不是张量的副本(元组)?

import torch

my_tensor = torch.tensor([[0, 1, 2, 3],
                          [4, 5, 6, 7],
                          [8, 9, 10, 11]])
torch.unbind(input=my_tensor)
# (tensor([0, 1, 2, 3]),
#  tensor([4, 5, 6, 7]),
#  tensor([8, 9, 10, 11]))

实际上,有类似的函数split()vsplit()hsplit()tensor_split()chunk(),然后他们的文档说他们返回张量的视图,而

unbind()
的文档只是说了张量的切片。

那么,

unbind()
返回张量的视图吗?

python pytorch tuples slice tensor
1个回答
0
投票

解除绑定返回一个视图。您可以通过查看

unbind
结果的数据指针来检查这一点。您还可以对原始张量进行变异,并看到
unbind
结果也发生了变异

x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
y = torch.unbind(x)

# check data pointers are the same
for i in range(len(y)):
    assert x[i].data_ptr() == y[i].data_ptr()

# mutate data of x
x.data[0] = torch.tensor([10,11,12])

# y[0] is also mutated
assert x[0] == y[0]

print(y[0])
> tensor([10, 11, 12])
© www.soinside.com 2019 - 2024. All rights reserved.