← 返回首页
🤖

逻辑回归:从原理到实战

📂 ai ⏱ 2 min 246 words

逻辑回归:从原理到实战

什么是逻辑回归

尽管名字中有"回归"二字,逻辑回归(Logistic Regression)实际上是一种分类算法。它通过Sigmoid函数将线性回归的输出映射到0-1之间,表示样本属于某个类别的概率。

Sigmoid函数

逻辑回归的核心是Sigmoid函数:

$$\sigma(z) = \frac{1}{1 + e^{-z}}$$

其中 $z = wx + b$ 是线性组合。

Sigmoid函数的特点:

逻辑回归原理

决策边界

逻辑回归使用线性决策边界:

损失函数

逻辑回归使用对数损失(Log Loss):

$$L = -\frac{1}{n}\sum_{i=1}^{n}[y_i\log(\hat{p}_i) + (1-y_i)\log(1-\hat{p}_i)]$$

代码示例:逻辑回归分类实战

import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (classification_report, confusion_matrix,
                             roc_auc_score, roc_curve)
import warnings
warnings.filterwarnings('ignore')

# 加载乳腺癌数据集
data = load_breast_cancer()
X, y = data.data, data.target
print(f"特征数: {X.shape[1]}, 样本数: {X.shape[0]}")
print(f"类别分布: 良性={sum(y==1)}, 恶性={sum(y==0)}")

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 数据标准化
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# 训练逻辑回归模型
lr = LogisticRegression(
    C=1.0,           # 正则化强度的倒数
    max_iter=1000,   # 最大迭代次数
    random_state=42
)
lr.fit(X_train_scaled, y_train)

# 预测
y_pred = lr.predict(X_test_scaled)
y_prob = lr.predict_proba(X_test_scaled)[:, 1]

# 模型评估
print("\n=== 模型评估 ===")
print(classification_report(y_test, y_pred, target_names=data.target_names))

# 混淆矩阵
cm = confusion_matrix(y_test, y_pred)
print("混淆矩阵:")
print(cm)

# ROC-AUC分数
roc_auc = roc_auc_score(y_test, y_prob)
print(f"\nROC-AUC分数: {roc_auc:.4f}")

# 交叉验证
cv_scores = cross_val_score(lr, X_train_scaled, y_train, cv=5, scoring='roc_auc')
print(f"5折交叉验证 AUC: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")

# 查看特征重要性(系数绝对值越大越重要)
feature_importance = np.abs(lr.coef_[0])
top_indices = np.argsort(feature_importance)[-5:][::-1]
print("\n最重要的5个特征:")
for idx in top_indices:
    print(f"  {data.feature_names[idx]}: {feature_importance[idx]:.4f}")

# 预测概率示例
print("\n预测概率示例(前5个测试样本):")
for i in range(5):
    prob = y_prob[i]
    pred = y_pred[i]
    actual = y_test[i]
    print(f"  样本{i+1}: 概率={prob:.4f}, 预测={data.target_names[pred]}, "
          f"实际={data.target_names[actual]}")

多分类扩展

逻辑回归可通过以下方式处理多分类问题:

# 多分类示例
from sklearn.datasets import load_iris

iris = load_iris()
X, y = iris.data, iris.target

lr_multi = LogisticRegression(
    multi_class='multinomial',
    solver='lbfgs',
    max_iter=200,
    random_state=42
)
lr_multi.fit(X, y)
print(f"\n多分类准确率: {lr_multi.score(X, y):.4f}")

逻辑回归的优缺点

优点:

缺点:

总结

逻辑回归是分类问题的基石算法,理解它对学习更复杂的分类模型至关重要。在实际应用中,逻辑回归因其高效和可解释性,仍然是许多场景的首选。