PyTorch神经网络构建与训练全解析
立即解锁
发布时间: 2025-09-05 01:51:49 阅读量: 135 订阅数: 10 AIGC 

### PyTorch 神经网络构建与训练全解析
#### 1. 特征标准化
在很多情况下,对特征进行标准化是一个很好的做法,即使并非总是必要(例如当所有特征都是二元特征时)。标准化的目的是让每个特征的值具有均值为 0 和标准差为 1 的特性。使用 scikit-learn 的 `StandardScaler` 可以轻松完成这一操作。
然而,如果你在创建了 `requires_grad=True` 的张量后需要进行标准化操作,就需要在 PyTorch 中直接实现,以免破坏计算图。以下是在 PyTorch 中实现特征标准化的代码:
```python
import torch
# Create features
torch_features = torch.tensor([[-100.1, 3240.1],
[-200.2, -234.1],
[5000.5, 150.1],
[6000.6, -125.1],
[9000.9, -673.1]], requires_grad=True)
# Compute the mean and standard deviation
mean = torch_features.mean(0, keepdim=True)
standard_deviation = torch_features.std(0, unbiased=False, keepdim=True)
# Standardize the features using the mean and standard deviation
torch_features_standardized = torch_features - mean
torch_features_standardized /= standard_deviation
# Show standardized features
print(torch_features_standardized)
```
运行上述代码后,输出的标准化特征如下:
```
tensor([[-1.1254, 1.9643],
[-1.1533, -0.5007],
[ 0.2953, -0.2281],
[ 0.5739, -0.4234],
[ 1.4096, -0.8122]], grad_fn=<DivBackward0>)
```
#### 2. 设计神经网络
当你想要设计一个神经网络时,可以使用 PyTorch 的 `nn.Module` 类来定义一个简单的神经网络架构。以下是具体的代码实现:
```python
import torch
import torch.nn as nn
# Define a neural network
class SimpleNeuralNet(nn.Module):
def __init__(self):
super(SimpleNeuralNet, self).__init__()
self.fc1 = nn.Linear(10, 16)
self.fc2 = nn.Linear(16, 16)
self.fc3 = nn.Linear(16, 1)
def forward(self, x):
x = nn.functional.relu(self.fc1(x))
x = nn.functional.relu(self.fc2(x))
x = nn.functional.sigmoid(self.fc3(x))
return x
# Initialize the neural network
network = SimpleNeuralNet()
# Define loss function, optimizer
loss_criterion = nn.BCELoss()
optimizer = torch.optim.RMSprop(network.parameters())
# Show the network
print(network)
```
输出的网络结构如下:
```
SimpleNeuralNet(
(fc1): Linear(in_features=10, out_features=16, bias=True)
(fc2): Linear(in_features=16, out_features=16, bias=True)
(fc3): Linear(in_features=16, out_features=1, bias=True)
)
```
在构建前馈神经网络时,需要在网络架构和训练过程方面做出一些选择。每个隐藏层单元的工作流程如下:
1. 接收多个输入。
2. 为每个输入乘以一个参数值进行加权。
3. 将所有加权输入与偏置(通常为 0)相加。
4. 通常会应用一个激活函数。
5. 将输出传递给下一层的单元。
在设计神经网络时,还需要考虑以下几个方面:
- **单元数量和激活函数**:对于隐藏层和输出层,需要定义每层包含的单元数量和激活函数。一般来说,层中的单元越多,网络能够学习的模式就越复杂,但也可能导致过拟合。对于隐藏层,常用的激活函数是修正线性单元(ReLU),其公式为 $f(z) = max(0, z)$。
- **隐藏层数量**:更多的隐藏层可以让网络学习更复杂的关系,但会增加计算成本。
- **输出层激活函数**:输出层激活函数的结构通常由网络的目标决定,常见的输出层模式如下表所示:
| 问题类型 | 输出层模式 |
| ---- | ---- |
| 二元分类 | 一个单元,使用 sigmoid 激活函数 |
| 多类分类 | k 个单元(k 为目标类别数),使用 softmax 激活函数 |
| 回归 | 一个单元,不使用激活函数 |
- **损失函数**:损失函数用于衡量预测值与真实值的匹配程度,常见的损失函数如下表所示:
| 问题类型 | 损失函数 |
| ---- | ---- |
| 二元分类 | 二元交叉熵 |
| 多类分类 | 类别交叉熵 |
| 回归 | 均方误差 |
- **优化器**:优化器可以看作是在损失函数上寻找产生最小误差的参数值的策略,常见的优化器有随机梯度下降、带动量的随机梯度下降、均方根传播和自适应矩估计等。
- **评估指标**:可以选择一个或多个指标来评估模型的性能,如准确率。
我们也可以使用 `Sequential` 类来定义神经网络,代码如下:
```python
import torch
# Define a neural network using `Sequential`
class SimpleNeuralNet(nn.Module):
def __init__(self):
super(SimpleNeuralNet, self).__init__()
self.sequential = torch.nn.Sequential(
torch.nn.Linear(10, 16),
torch.nn.ReLU(),
torch.nn.Linear(16,16),
torch.nn.ReLU(),
torch.nn.Linear(16, 1),
torch.nn.Sigmoid()
)
def forward(self, x):
x = self.sequential(x)
return x
# Instantiate and view the network
print(SimpleNeuralNet())
```
输出的网络结构如下:
```
SimpleNeuralNet(
(sequential): Sequential(
(0): Linear(in_features=10, out_features=16, bias=True)
(1): ReLU()
(2): Linear(in_features=16, out_features=16, bias=True)
(3): ReLU()
(4): Linear(in_features=16, out_features=1, bias=True)
(5): Sigmoid()
)
)
```
这个网络是一个两层的神经网络(计算层数时不包括输入层,因为输入层没有需要学习的参数),每个层都是“密集”(也称为“全连接”)的,即前一层的所有单元都连接到下一层的所有单元。
#### 3. 训练二元分类器
如果你想训练一个二元分类器神经网络,可以使用 PyTorch 构建前馈神经网络并进行训练。具体步骤如下:
1. **导入必要的库**:
```python
import torch
import torch.nn as nn
import numpy as np
from torch.utils.data import DataLoader, TensorDataset
from torch.optim import RMSprop
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
```
2. **创建训练集和测试集**:
```python
features, target = make_classification(n_classes=2, n_features=10, n_samples=1000)
features_train, features_test, target_train, target_test = train_test_split(
features, target, test_size=0.1, random_state=1)
```
3. **设置随机种子**:
```python
torch.manual_seed(0)
np.random.seed(0)
```
4. **将数据转换为 PyTorch 张量**:
```python
x_train = torch.from_numpy(features_train).float()
y_train = torch.from_numpy(target_train).float().view(-1, 1)
x_test = torch.from_numpy(features_test).float()
y_test = torch.from_numpy(target_test).float().v
```
0
0
复制全文
相关推荐










