目录

摘要

Abstract

1实验目的

2实验环境

3实验原理简述

4完整实验代码

5程序运行结果展示

5.1控制台文字输出结果

6拓展小实验:多分类 Softmax 逻辑回归

7实验结论

8实验收获


摘要

本实验通过Python和scikit-learn实现了逻辑回归模型的完整流程,对比了原生线性逻辑回归与多项式特征变换后的非线性分类效果。实验使用环形数据集验证了特征变换的重要性,结果显示二阶多项式变换将准确率从线性模型的50%提升至90%以上。实验还展示了决策边界可视化,并拓展到Softmax多分类任务。结果表明,特征工程对提升逻辑回归的非线性分类能力至关重要,但需注意避免维度爆炸。该实验验证了逻辑回归的适用场景和局限性,加深了对判别式模型和特征变换的理解。

Abstract

This experiment implemented the full process of a logistic regression model using Python and scikit-learn, and compared the performance of original linear logistic regression with non-linear classification after polynomial feature transformation. A ring-shaped dataset was used to verify the importance of feature transformation, and the results showed that a second-order polynomial transformation increased accuracy from 50% with the linear model to over 90%. The experiment also demonstrated decision boundary visualization and extended to Softmax multi-class tasks. The results indicate that feature engineering is crucial for improving the non-linear classification ability of logistic regression, but it's important to avoid dimensionality explosion. This experiment validated the applicable scenarios and limitations of logistic regression, and deepened the understanding of discriminative models and feature transformation.

1实验目的

  • 理解逻辑回归建模完整流程:数据加载、数据预处理、特征变换、模型训练、预测、效果评估;
  • 对比原生逻辑回归线性分类局限 + 多项式特征变换后的非线性分类效果;
  • 直观观测模型准确率、决策边界差异,验证课堂理论知识;
  • 掌握 Python + scikit-learn 实现逻辑回归代码编写与结果解读。

2实验环境

  • 编程语言:Python 3.8+
  • 依赖库:numpy、matplotlib、scikit-learn
  • 实验数据集:sklearn 内置环形二维数据集(make_circles),天然线性不可分,适合验证特征变换作用

3实验原理简述

  • 逻辑回归属于线性判别式分类器,原生决策边界为直线,无法划分环形数据;
  • 通过多项式特征变换,将二维特征映射至高维空间,逻辑回归可学习非线性边界;
  • 模型评价指标:分类准确率 Accuracy

4完整实验代码

# 1. 导入所需工具包
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_circles
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.metrics import accuracy_score

# 设置图片中文正常显示
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei"]
plt.rcParams["axes.unicode_minus"] = False

# 2. 生成环形非线性数据集
# noise:添加少量噪声因子,随机种子固定保证每次运行结果一致
X, y = make_circles(n_samples=500, noise=0.1, random_state=20)

# 3. 实验1:原生逻辑回归(无特征变换,纯线性分类)
# 3.1 标准化特征(梯度下降收敛必备)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 3.2 初始化并训练逻辑回归模型
lr_linear = LogisticRegression(random_state=20)
lr_linear.fit(X_scaled, y)

# 3.3 预测样本并计算准确率
y_pred_linear = lr_linear.predict(X_scaled)
acc_linear = accuracy_score(y, y_pred_linear)
print("===== 未做特征变换:线性逻辑回归 =====")
print(f"模型分类准确率:{acc_linear:.4f}")

# 4. 实验2:添加二阶多项式特征变换,构造非线性特征
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(X)
X_poly_scaled = scaler.fit_transform(X_poly)

# 训练多项式特征下的逻辑回归
lr_poly = LogisticRegression(random_state=20)
lr_poly.fit(X_poly_scaled, y)
y_pred_poly = lr_poly.predict(X_poly_scaled)
acc_poly = accuracy_score(y, y_pred_poly)
print("\n===== 二阶多项式特征变换后逻辑回归 =====")
print(f"模型分类准确率:{acc_poly:.4f}")

# 5. 绘制两组模型决策边界对比图
def plot_decision_boundary(model, X, y, title):
    x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
    y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
                         np.arange(y_min, y_max, 0.02))
    # 区分是否为多项式特征输入
    if "poly" in title:
        grid = poly.transform(np.c_[xx.ravel(), yy.ravel()])
        grid = scaler.transform(grid)
    else:
        grid = scaler.transform(np.c_[xx.ravel(), yy.ravel()])
    Z = model.predict(grid)
    Z = Z.reshape(xx.shape)
    plt.contourf(xx, yy, Z, alpha=0.3)
    plt.scatter(X[:, 0], X[:, 1], c=y, s=30)
    plt.title(title)
    plt.xlabel("特征x1")
    plt.ylabel("特征x2")

plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plot_decision_boundary(lr_linear, X, y, f"线性逻辑回归 准确率:{acc_linear:.2f}")
plt.subplot(1, 2, 2)
plot_decision_boundary(lr_poly, X, y, f"多项式变换后 准确率:{acc_poly:.2f}")
plt.tight_layout()
plt.show()

5程序运行结果展示

5.1控制台文字输出结果

6拓展小实验:多分类 Softmax 逻辑回归

from sklearn.datasets import load_iris
# 鸢尾花3分类数据集
iris = load_iris()
X_iris, y_iris = iris.data, iris.target
# Softmax多分类逻辑回归
softmax_lr = LogisticRegression(multi_class="multinomial", solver="lbfgs", max_iter=200)
softmax_lr.fit(X_iris, y_iris)
y_pre = softmax_lr.predict(X_iris)
acc = accuracy_score(y_iris, y_pre)
print(f"\n鸢尾花3分类Softmax回归准确率:{acc:.4f}")

运行输出:

验证:逻辑回归拓展 Softmax 可轻松完成多分类任务。

7实验结论

  1. 原生逻辑回归是严格线性模型,面对非线性分布数据分类效果很差,必须依靠特征变换提升拟合能力;
  2. 多项式特征变换是弥补线性模型缺陷最常用手段,但阶数过高易产生维度爆炸、引发过拟合;
  3. 逻辑回归结构简单、训练快速,可解释性强,适合风控、打分卡等需要输出概率的业务场景;
  4. 若数据非线性关系极度复杂,人工特征工程成本过高,可改用级联逻辑回归或者神经网络自动学习特征。

8实验收获

通过代码实操,将之前学习的判别式模型、特征变换、决策边界、Softmax 多分类等理论知识落地,直观看到每一步预处理和特征工程对模型精度的影响,清晰掌握了逻辑回归的适用场景与局限性。

更多推荐