您好,登录后才能下订单哦!
# PyTorch基础中的逻辑回归是怎么样的
## 引言:从线性回归到分类问题
在机器学习领域,**逻辑回归**(Logistic Regression)是一个看似简单却极为重要的算法。虽然名称中带有"回归"二字,但它实际上是解决**分类问题**的经典方法。与线性回归直接预测连续值不同,逻辑回归通过引入**Sigmoid函数**将线性输出转换为概率值,从而实现对类别的预测。
PyTorch作为当前最流行的深度学习框架之一,其动态计算图和自动微分机制使得实现逻辑回归变得异常简洁。本文将深入探讨:
1. 逻辑回归的数学原理
2. PyTorch实现的核心步骤
3. 实际应用中的关键细节
4. 扩展与优化方法
## 一、逻辑回归的数学基础
### 1.1 从线性到非线性
逻辑回归的核心公式可以表示为:
$$ z = w^T x + b $$
$$ \hat{y} = \sigma(z) = \frac{1}{1+e^{-z}} $$
其中:
- $w$ 是权重向量
- $b$ 是偏置项
- $\sigma$ 是Sigmoid函数
### 1.2 Sigmoid函数的特性
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 100)
y = 1 / (1 + np.exp(-x))
plt.plot(x, y)
plt.title("Sigmoid Function")
plt.show()
Sigmoid函数将任意实数映射到(0,1)区间,这个特性使其非常适合表示概率。
逻辑回归使用二元交叉熵损失(Binary Cross Entropy):
\[ L = -\frac{1}{N}\sum_{i=1}^N [y_i \log(\hat{y}_i) + (1-y_i)\log(1-\hat{y}_i)] \]
在PyTorch中对应nn.BCELoss()
。
import torch
import torch.nn as nn
# 1. 准备数据
X = torch.tensor([[1.0], [2.0], [3.0], [4.0]])
y = torch.tensor([[0], [0], [1], [1]], dtype=torch.float32)
# 2. 定义模型
class LogisticRegression(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(1, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
return self.sigmoid(self.linear(x))
model = LogisticRegression()
# 3. 定义损失和优化器
criterion = nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
# 4. 训练循环
for epoch in range(100):
# 前向传播
outputs = model(X)
loss = criterion(outputs, y)
# 反向传播
optimizer.zero_grad()
loss.backward()
optimizer.step()
对于多分类问题,只需将Sigmoid替换为Softmax:
model = nn.Sequential(
nn.Linear(input_dim, num_classes),
nn.Softmax(dim=1)
)
criterion = nn.CrossEntropyLoss() # 已包含Softmax
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_normalized = scaler.fit_transform(X)
建议使用学习率调度器:
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)
from sklearn.metrics import accuracy_score, confusion_matrix
with torch.no_grad():
predictions = (model(X_test) > 0.5).float()
acc = accuracy_score(y_test, predictions)
L2正则化(权重衰减):
optimizer = torch.optim.Adam(model.parameters(), weight_decay=1e-4)
class WeightedBCELoss(nn.Module):
def __init__(self, pos_weight):
super().__init__()
self.pos_weight = pos_weight
def forward(self, y_pred, y_true):
loss = - (self.pos_weight * y_true * torch.log(y_pred) +
(1 - y_true) * torch.log(1 - y_pred))
return loss.mean()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
X, y = X.to(device), y.to(device)
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
# 数据加载与预处理
data = load_breast_cancer()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# 转换为Tensor
X_train = torch.FloatTensor(X_train)
y_train = torch.FloatTensor(y_train).reshape(-1, 1)
# 定义模型
model = nn.Sequential(
nn.Linear(30, 1),
nn.Sigmoid()
)
# 训练过程
for epoch in range(1000):
optimizer.zero_grad()
outputs = model(X_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
尽管深度学习已经发展出更复杂的模型,逻辑回归仍然因其: 1. 计算效率高 2. 可解释性强 3. 作为神经网络的基础组件
在工业界保持着广泛应用。通过PyTorch的实现,我们不仅能快速构建模型,还能无缝衔接到更复杂的神经网络结构中。
延伸阅读: - PyTorch官方文档 - 《深度学习入门》- 斋藤康毅 - 机器学习系统设计中的逻辑回归应用 “`
注:本文实际字数约2850字(含代码),主要包含: 1. 数学原理讲解(约600字) 2. PyTorch实现详解(约800字) 3. 实战技巧(约700字) 4. 案例与扩展(约750字) 格式完整支持Markdown渲染,可直接用于技术博客或文档。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。