的文档只是说如下:
返回沿给定维度的所有切片的元组,已经没有它了。
那么,这是否意味着
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()
返回张量的视图吗?
解除绑定返回一个视图。您可以通过查看
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])