在 PyTorch 中,`torch`, `torch.nn`, 和 `torch.nn.functional` 是三个非常重要的模块,它们分别提供了深度学习所需的基本构件、层次结构、以及功能函数。
### 1. `torch`
`torch` 是 PyTorch 的核心模块,提供了张量操作、随机数生成、数学计算等基础功能。常见作用包括:
- **张量创建与操作**:
```python
x = torch.tensor([1, 2, 3]) # 创建张量
y = torch.zeros((3, 3)) # 创建一个全零的3x3矩阵
z = torch.rand((2, 2)) # 创建一个2x2的随机矩阵
```
- **GPU 支持**:
```python
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = x.to(device) # 将张量移动到GPU
```
- **数学运算**:
```python
result = torch.matmul(x, y) # 矩阵乘法
result = torch.sum(x) # 求和
```
### 2. `torch.nn`
`torch.nn` 是 PyTorch 中定义神经网络模块的包,包含了各种常用的神经网络层、损失函数、容器等。常见作用包括:
- **神经网络层**:
```python
linear = nn.Linear(in_features=10, out_features=5) # 线性层
conv = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3) # 卷积层
```
- **损失函数**:
```python
loss_fn = nn.CrossEntropyLoss() # 交叉熵损失
```
- **容器类**:用于构建更复杂的模型。
```python
model = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=3),
nn.ReLU(),
nn.MaxPool2d(2)
)
```
### 3. `torch.nn.functional`
`torch.nn.functional` 提供了各种操作和函数,这些函数主要用于对张量进行操作,并与 `torch.nn` 中的层搭配使用。与 `torch.nn` 中的模块不同的是,`torch.nn.functional` 中的函数通常是无状态的。常见作用包括:
- **激活函数**:
```python
x = torch.randn(10)
out = F.relu(x) # ReLU 激活函数
```
- **卷积操作**:
```python
out = F.conv2d(input, weight) # 2D 卷积操作
```
- **归一化操作**:
```python
out = F.batch_norm(input, running_mean, running_var) # Batch Normalization
```
- **损失函数**:尽管很多损失函数在 `torch.nn` 中作为类实现,但在 `torch.nn.functional` 中,它们也以函数的形式存在。
```python
loss = F.cross_entropy(output, target) # 交叉熵损失
```
总结来说:
- `torch` 提供基础的张量操作和数学计算功能。
- `torch.nn` 提供用于构建神经网络的层、容器和损失函数。
- `torch.nn.functional` 提供无状态的函数,用于操作张量和计算损失。