Scikit-learn 1.4.2 逻辑回归实战:鸢尾花二分类准确度 95%+ 调优指南

📅 2026/7/8 11:47:03
Scikit-learn 1.4.2 逻辑回归实战:鸢尾花二分类准确度 95%+ 调优指南
Scikit-learn 1.4.2 逻辑回归实战鸢尾花二分类准确度 95% 调优指南1. 理解逻辑回归的核心机制逻辑回归作为经典的分类算法其核心在于通过Sigmoid函数将线性预测结果映射为概率。在Scikit-learn 1.4.2版本中算法的底层实现经过优化特别在处理中小规模数据集时展现出更高的效率。Sigmoid函数的数学表达def sigmoid(z): return 1 / (1 np.exp(-z))该函数将线性组合 $z w^Tx b$ 转换为(0,1)区间的概率值。当$z0$时概率为0.5这正是决策边界的位置。关键参数解析penalty: 正则化类型l2或l1C: 正则化强度的倒数值越小正则化越强solver: 优化算法选择lbfgs、liblinear等2. 数据准备与特征工程鸢尾花数据集包含三类样本我们首先将其转换为二分类问题from sklearn.datasets import load_iris import numpy as np iris load_iris() X iris.data[:, :2] # 仅使用前两个特征便于可视化 y (iris.target ! 0).astype(int) # 将类别1和2合并为1类特征标准化的重要性 虽然逻辑回归不需要严格的正态分布输入但标准化能显著提升优化效率from sklearn.preprocessing import StandardScaler scaler StandardScaler() X_scaled scaler.fit_transform(X)3. 基础模型构建与评估建立基线模型是调优的起点from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test train_test_split(X_scaled, y, test_size0.2, random_state42) base_model LogisticRegression(penaltyl2, C1.0, solverlbfgs, max_iter100) base_model.fit(X_train, y_train)评估指标对比指标训练集测试集准确度0.950.93ROC AUC0.980.96F1 Score0.940.92提示当类别不平衡时准确度可能产生误导应优先关注ROC AUC和F1 Score4. 三阶段调优策略4.1 特征选择优化通过分析特征重要性可以精简模型并提升泛化能力coef_df pd.DataFrame({ feature: iris.feature_names[:2], coefficient: base_model.coef_[0], abs_coef: np.abs(base_model.coef_[0]) }).sort_values(abs_coef, ascendingFalse)特征组合实验 尝试不同特征组合对模型性能的影响特征组合测试准确度仅花萼长度0.87仅花萼宽度0.83花萼长度宽度0.93所有四个特征0.964.2 正则化参数C的调优正则化强度是影响模型复杂度的关键参数from sklearn.model_selection import GridSearchCV param_grid {C: np.logspace(-3, 3, 7)} grid_search GridSearchCV(LogisticRegression(penaltyl2, solverlbfgs), param_grid, cv5, scoringaccuracy) grid_search.fit(X_scaled, y)C值影响规律过小如0.001欠拟合决策边界过于平滑适中0.1-1最佳平衡点过大100可能过拟合4.3 求解器(solver)对比测试不同优化算法对结果的影响求解器收敛速度内存效率适合场景liblinear快低小数据集lbfgs中等高中型数据集(默认)sag/saga慢高超大数据集性能对比代码solvers [liblinear, lbfgs, sag] for solver in solvers: model LogisticRegression(solversolver, max_iter1000) scores cross_val_score(model, X_scaled, y, cv5) print(f{solver}: 平均准确度{scores.mean():.3f})5. 高级调优技巧5.1 类别权重调整处理不平衡数据的两种方法方法一class_weight参数balanced_model LogisticRegression(class_weightbalanced, C0.1)方法二样本重采样from imblearn.over_sampling import SMOTE smote SMOTE(random_state42) X_res, y_res smote.fit_resample(X_train, y_train)5.2 多项式特征扩展通过特征工程突破线性限制from sklearn.preprocessing import PolynomialFeatures poly PolynomialFeatures(degree2, include_biasFalse) X_poly poly.fit_transform(X_scaled) poly_model LogisticRegression(C0.1, max_iter1000) poly_model.fit(X_poly, y)6. 完整优化代码示例from sklearn.pipeline import make_pipeline from sklearn.metrics import classification_report # 构建完整管道 pipeline make_pipeline( StandardScaler(), PolynomialFeatures(degree2), LogisticRegression(penaltyl2, C0.1, class_weightbalanced, solverlbfgs) ) # 训练与评估 pipeline.fit(X_train, y_train) y_pred pipeline.predict(X_test) print(classification_report(y_test, y_pred)) # 获取最终模型参数 final_model pipeline.named_steps[logisticregression] print(f模型系数: {final_model.coef_})7. 决策边界可视化理解模型如何划分特征空间def plot_decision_boundary(model, X, y): x_min, x_max X[:, 0].min() - 1, X[:, 0].max() 1 y_min, y_max X[:, 1].min() - 1, X[:, 1].max() 1 xx, yy np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) Z model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) plt.contourf(xx, yy, Z, alpha0.3) plt.scatter(X[:, 0], X[:, 1], cy, edgecolorsk) plt.xlabel(标准化花萼长度) plt.ylabel(标准化花萼宽度) plt.title(逻辑回归决策边界)8. 生产环境部署建议模型持久化import joblib joblib.dump(pipeline, iris_lr_model.pkl)性能监控指标实时准确率预测延迟输入特征分布偏移检测定期再训练机制 设置自动化流水线当性能下降超过阈值时触发再训练