当前位置: 首页 > news >正文

机器学习-逻辑回归模型完整的训练流程

本文演示如何使用逻辑回归对鸢尾花数据集进行分类:

注:使用scikit-learn的逻辑回归

1.数据下载

# 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix# 加载数据
iris = load_iris()
X, y = iris.data, iris.target
feature_names = iris.feature_names
target_names = iris.target_namesprint("特征名称:", feature_names)
print("目标类别:", target_names)
print(f"数据集形状: X={X.shape}, y={y.shape}")

 2.数据预处理

# 划分训练集和测试集
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)print("原始数据均值:\n", X_train.mean(axis=0))
print("缩放后数据均值:\n", X_train_scaled.mean(axis=0))

  3.训练逻辑回归模型

  1. 多分类策略:

    • ovr (一对多): 为每个类别训练一个二分类器

    • multinomial (多项式): 直接使用 softmax 回归

  2. 训练过程: 通过最大似然估计找到最佳参数,最小化对数损失
# 创建并训练模型
model = LogisticRegression(multi_class='ovr',        # 多分类策略:'ovr'(一对多) 或 'multinomial'(多项式)solver='lbfgs',           # 优化算法max_iter=1000,            # 最大迭代次数random_state=42
)model.fit(X_train_scaled, y_train)# 查看模型参数
print("模型系数:\n", model.coef_)
print("模型截距:\n", model.intercept_)
print("迭代次数:", model.n_iter_[0])

4. 概率估算和预测

逻辑回归模型跟线性回归模型一样,是计算输入特征的加权和(加上偏置项),但是不同于线性回归模型直接输出结果,它输出的是结果的数量逻辑值。

简单理解,概率估算就是逻辑回归模型通过 sigmoid 函数(二分类)或 softmax 函数(多分类)将线性输出结果转换为概率。

 

预测决策: 选择概率最高的类别作为预测结果

 

# 预测概率(核心步骤)
y_proba = model.predict_proba(X_test_scaled)# 显示前5个样本的预测概率
print("\n前5个样本的预测概率:")
print(pd.DataFrame(y_proba[:5], columns=target_names,index=[f'样本{i+1}' for i in range(5)]
))# 预测类别(基于最高概率)
y_pred = model.predict(X_test_scaled)print("\n前5个样本的预测结果:")
for i in range(5):pred_class = target_names[y_pred[i]]true_class = target_names[y_test[i]]prob = y_proba[i].max()print(f"样本{i+1}: 预测={pred_class}, 实际={true_class}, 置信度={prob:.2%}")

  

5. 模型评估

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"准确率: {accuracy:.2%}")# 详细分类报告
print("\n分类报告:")
print(classification_report(y_test, y_pred, target_names=target_names))# 混淆矩阵
cm = confusion_matrix(y_test, y_pred)
print("混淆矩阵:")
print(cm)# 可视化混淆矩阵
import seaborn as sns
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',xticklabels=target_names, yticklabels=target_names)
plt.title('混淆矩阵')
plt.xlabel('预测类别')
plt.ylabel('实际类别')
plt.show()

6. 超参数调优

使用sklearn的网格搜索,只需要告诉它希望实验哪些超参数以及要尝试的值,它会使用交叉验证来评估所有可能的超参数值的组合。

from sklearn.model_selection import GridSearchCV# 定义参数网格
param_grid = {'C': [0.01, 0.1, 1, 10, 100],  # 正则化强度的倒数'solver': ['lbfgs', 'newton-cg', 'sag'],'multi_class': ['ovr', 'multinomial']
}# 网格搜索
grid_search = GridSearchCV(LogisticRegression(max_iter=1000, random_state=42),param_grid,cv=5,scoring='accuracy',n_jobs=-1
)grid_search.fit(X_train_scaled, y_train)print("最佳参数:", grid_search.best_params_)
print("最佳交叉验证分数:", grid_search.best_score_)# 使用最佳模型
best_model = grid_search.best_estimator_
y_pred_best = best_model.predict(X_test_scaled)
accuracy_best = accuracy_score(y_test, y_pred_best)
print(f"测试集准确率: {accuracy_best:.2%}")

  

http://www.jsqmd.com/news/443258/

相关文章:

  • 2026年呼叫中心系统集成厂商推荐及厂商技术支持详解 - 品牌2026
  • 千问48小时人事巨震始末:技术理想与商业化的激烈碰撞
  • Token消耗量快速增长引爆AI应用;腾讯应用宝推出跨端开放平台
  • OpenClaw 智能体本地部署和使用并与飞书连接
  • 2026年客服系统厂商:无缝对接微信公众号+企业微信,赋能服务 - 品牌2026
  • 50岁程序员重生:医疗AI领域的二次创业
  • 数据铸就现实:工业级虚拟游戏真实感核心底座
  • 用Claude打造原生律所!两人顶千人的律所降维打击
  • 2026男士洗面奶红黑榜,别再乱买啦! - 品牌测评鉴赏家
  • 考研后申请美国看案例?美国留学中介录取榜单排名全公开 - 博客湾
  • 电加热导热油炉价格多少,推荐几家靠谱的生产厂家 - 工业品牌热点
  • 考研后想去美国读研?美国留学中介名校录取率排名大揭秘 - 博客湾
  • 火语言RPA:倒计时弹窗案例
  • 2026郑州装修公司排名出炉,华埔装饰口碑出色性价比超预期 - mypinpai
  • 考研后想冲美国读研?美国留学中介实力口碑排名优选 - 博客湾
  • 男士洗面奶哪家好?实测5家爆款,油皮/敏肌/学生党按需冲不踩雷 - 品牌测评鉴赏家
  • 2026年衬衫采购/定制必看:商捷服饰用25年技术打造功能衬衫全场景解决方案 - 速递信息
  • 2026年2月,看重庆火锅必吃榜的惊艳之处,火锅/美食/火锅店/社区火锅/特色美食,火锅品牌排行 - 品牌推荐师
  • 有哪些值得推荐的短链接API生成接口?
  • 考研后想拿美国奖学金?美国留学中介奖学金申请排名看这里 - 博客湾
  • 2026年名企就业规划机构费用多少,衔芦职导收费合理 - 工业品网
  • 考研后想稳申美国读研?2026美国留学中介靠谱之选 - 博客湾
  • 蒙特环境常见问题解答(2026最新专家版) - 速递信息
  • 讲讲北京的AI搜索优化公司费用,北京锡禹科技性价比如何? - myqiye
  • 2026选购导热油炉,这些口碑不错的厂家你不能错过 - 工业品牌热点
  • 开学了—来场酣畅淋漓的装备升级吧
  • 2026吸塑源头厂家趋势报告:三大核心力量重塑行业 - 速递信息
  • 2026年天津靠谱装修公司排名,美馨装饰性价比超高 - 工业推荐榜
  • 北京居住证——AWS解决方案架构师
  • 2026年全封闭管教学校哪家好,江西宜春博智青少年叛逆学校值得选 - mypinpai