pytorch -- expand 和 expand_as

1. expand(size)

Example:

x = torch.rand(1,2,3)
print(x)
print("x.shape:", x.shape)
y = x.expand(2, 2,3)
print(y)
print("y.shape:", y.shape)

Output:

tensor([[[0.8020, 0.2300, 0.8632],
         [0.9463, 0.0172, 0.9756]]])
x.shape: torch.Size([1, 2, 3])

tensor([[[0.8020, 0.2300, 0.8632],
         [0.9463, 0.0172, 0.9756]],

        [[0.8020, 0.2300, 0.8632],
         [0.9463, 0.0172, 0.9756]]])
y.shape: torch.Size([2, 2, 3])

Note
expand only on the number of dimensions in tensor is operated to be extended to a dimension of, for example, the example above only the first extended dimension, if the change x.expand(1, 4, 3)being given, expand_as line presentation face and expand almost the same, expand_as and out parameter is a tensor

2. tensor.expand_as(tensor1)

Example:

x = torch.rand(1,2,3)
z = torch.rand(3, 2,3)
print(x)
print("x.shape:", x.shape)
y = x.expand_as(z)
print(y)
print("y.shape:", y.shape)

Output:

tensor([[[0.5696, 0.3571, 0.2565],
         [0.9646, 0.5754, 0.7819]]])
x.shape: torch.Size([1, 2, 3])

tensor([[[0.5696, 0.3571, 0.2565],
         [0.9646, 0.5754, 0.7819]],

        [[0.5696, 0.3571, 0.2565],
         [0.9646, 0.5754, 0.7819]],

        [[0.5696, 0.3571, 0.2565],
         [0.9646, 0.5754, 0.7819]]])
y.shape: torch.Size([3, 2, 3])
Published 33 original articles · won praise 1 · views 2609

Guess you like

Origin blog.csdn.net/orangerfun/article/details/104029156