torch.expand_dims
时间: 2023-09-10 08:11:35 浏览: 172
`torch.expand_dims`是PyTorch中的一个函数,用于在给定维度上扩展张量的形状。它的作用类似于NumPy中的`np.expand_dims`函数。
具体而言,`torch.expand_dims(input, dim)`会在输入张量`input`的指定维度`dim`上插入一个维度,从而扩展张量的形状。例如,如果`input`是一个形状为(3, 4)的张量,而`dim=0`,则`torch.expand_dims(input, dim)`将返回一个形状为(1, 3, 4)的张量,其中第一个维度被插入到原始张量的第0个维度上。
下面是一个示例:
```python
import torch
x = torch.randn(3, 4)
print(x.shape) # 输出: torch.Size([3, 4])
# 在维度0上扩展张量
y = torch.expand_dims(x, 0)
print(y.shape) # 输出: torch.Size([1, 3, 4])
# 在维度1上扩展张量
z = torch.expand_dims(x, 1)
print(z.shape) # 输出: torch.Size([3, 1, 4])
```
在这个示例中,我们首先创建了一个形状为(3, 4)的张量`x`。然后,我们使用`torch.expand_dims`函数在维度0和1上分别扩展了张量。注意,在维度0上扩展张量会在新的第0维上插入一个维度,因此输出的形状为(1, 3, 4)。而在维度1上扩展张量会在新的第1维上插入一个维度,因此输出的形状为(3, 1, 4)。
阅读全文
相关推荐

















