torch.Tensor.expand_as
官方文档地址:https://pytorch.org/docs/stable/generated/torch.Tensor.expand_as.html?highlight=expand_as#torch.Tensor.expand_as
torch.Tensor.expand()
官方文档地址:https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html#torch.Tensor.expand
torch.Tensor.expand()
形式:Tensor.expand(*sizes) → Tensor
作用:返回这个张量的一个新视图,其中单例维度扩展为更大的尺寸。传入 -1 作为维度的大小意味着不更改该维度的大小。Tensor 也可以扩展到更大的维度,新的维度会附加在前面。对于新维度,大小不能设置为 -1。扩展张量不会分配新内存,而只会在现有张量上创建一个新视图,其中通过将步幅设置为 0 将尺寸为 1 的维度扩展为更大的尺寸。任何大小为 1 的维度都可以扩展为任意值,而无需分配新的内存。
参数:
*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]])
说明: expand()
函数只能将size=1的维度扩展到更大的尺寸,如果扩展其他size的维度会报错。
torch.Tensor.expand_as
形式:Tensor.expand_as(other) → Tensor
作用:将此张量扩展为与其他张量相同的大小。 self.expand_as(other)
等价于 self.expand(other.size())
。
参数:
other (torch.Tensor) – The result tensor has the same size as other.