torch.Tensor.expand
- Tensor.expand(*sizes) Tensor
Returns a new view of the
self
tensor with singleton dimensions expanded to a larger size.
返回一个新的视图,其中self
张量的单一维度扩展到更大的尺寸。Passing -1 as the size for a dimension means not changing the size of that dimension.
将某个维度的大小设为-1 表示不改变该维度的大小。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.
张量也可以扩展到更多的维度,新维度将添加在前面。对于新维度,大小不能设为-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.
扩展张量不会分配新的内存,只会在现有张量上创建一个新的视图,其中大小为 1 的维度通过将stride
设置为 0 扩展到更大的尺寸。任何大小为 1 的维度都可以扩展到任意值而无需分配新内存。- Parameters 参数
*sizes (torch.Size or int...) – the desired expanded size
*sizes (torch.Size 或 int...) – 所需的扩展尺寸
Warning 警告
More than one element of an expanded tensor may refer to a single memory location. As a result, in-place operations (especially ones that are vectorized) may result in incorrect behavior. If you need to write to the tensors, please clone them first.
扩展张量的多个元素可能指向同一个内存位置。因此,就地操作(尤其是向量化操作)可能会导致不正确的行为。如果需要对张量进行写操作,请先克隆它们。Example: 示例:
>>> 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]])