Tensor.expand

函数定义

Tensor.expand(*sizes) → Tensor

Returns a new view of the self tensor with singleton(一个,单个) dimensions expanded to a larger size.

Passing -1 as the size for a dimension means not changing the size of that dimension.

Tensor can be also expanded to a larger number of dimensions, and the new ones will be appended at the front. For the new dimensions, the size cannot be set to -1.

Expanding a tensor does not allocate new memory, but only creates a new view on the existing tensor where a dimension of size one is expanded to a larger size by setting the stride to 0. Any dimension of size 1 can be expanded to an arbitrary value without allocating new memory.

参数

*sizes (torch.Size or int...) – the desired expanded size

例子

>>> x = torch.tensor([[1], [2], [3]])
>>> x.size()
torch.Size([3, 1])
>>> x.expand(3, 4)
tensor([[ 1,  1,  1,  1],
        [ 2,  2,  2,  2],
        [ 3,  3,  3,  3]])
>>> x.expand(-1, 4)   # -1 means not changing the size of that dimension
tensor([[ 1,  1,  1,  1],
        [ 2,  2,  2,  2],
        [ 3,  3,  3,  3]])
a = torch.ones(3,1).float()
b = a.expand(3,4)
print(a.data_ptr(),b.data_ptr())
a[0,0] = 3
print(a)
print(b)
94469097862528 94469097862528
tensor([[3.],
        [1.],
        [1.]])
tensor([[3., 3., 3., 3.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])

posted on 2021-08-05 21:46  朴素贝叶斯  阅读(207)  评论(0编辑  收藏  举报

导航