二分类-多机器学习模型算法实现对比

准备数据

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import PolynomialFeatures
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
# 读取数据
train = pd.read_csv("train.csv")
# print(train.head())
# 列出需要标准化的数值型特征和需要独热编码的类别型特征
numeric_features = ['age', 'duration', 'campaign', 'pdays', 'previous', 'emp_var_rate', 'cons_price_index', 'cons_conf_index', 'lending_rate3m', 'nr_employed']
categorical_features = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome']
# 定义ColumnTransformer
preprocessor = ColumnTransformer(transformers=[('poly', PolynomialFeatures(degree=3, include_bias=False), numeric_features),  # 标准化数值型特征('cat', OneHotEncoder(), categorical_features)  # 独热编码类别型特征])
# 定义包含数据处理和特征工程的Pipeline
preprocessing_pipeline = Pipeline([('preprocessor', preprocessor)  # 数据处理和特征工程
])
# 在训练集上拟合数据处理和特征工程的Pipeline
X_transformed = preprocessing_pipeline.fit_transform(train)
y = train["subscribe"].apply(lambda x: 1 if x == "yes" else 0)

模型训练和结果

使用逻辑回归/决策树/随机森林算法

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, accuracy_score, roc_curve, auc
import seaborn as sns# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_transformed, y, test_size=0.3, random_state=42)# 定义模型
models = {'Logistic Regression': LogisticRegression(max_iter=1000),'Decision Tree': DecisionTreeClassifier(),'Random Forest': RandomForestClassifier(n_estimators=100)
}# 字典存储结果
results = {}for model_name, model in models.items():# 训练模型model.fit(X_train, y_train)# 预测y_pred = model.predict(X_test)# 评估accuracy = accuracy_score(y_test, y_pred)cm = confusion_matrix(y_test, y_pred)# 计算ROC曲线和AUCy_prob = model.predict_proba(X_test)[:, 1]fpr, tpr, _ = roc_curve(y_test, y_prob)roc_auc = auc(fpr, tpr)results[model_name] = {'accuracy': accuracy,'confusion_matrix': cm,'fpr': fpr,'tpr': tpr,'roc_auc': roc_auc}# 输出准确率
for name, metrics in results.items():print(f"{name} Accuracy: {metrics['accuracy']:.2f} - AUC: {metrics['roc_auc']:.2f}")

Logistic Regression Accuracy: 0.87 - AUC: 0.82

Decision Tree Accuracy: 0.83 - AUC: 0.65

Random Forest Accuracy: 0.88 - AUC: 0.88

数据可视化

# 1. 绘制混淆矩阵
plt.figure(figsize=(15, 5))  # 创建新的图形并设置大小
for i, (model_name, metrics) in enumerate(results.items()):plt.subplot(1, 3, i + 1)  # 将混淆矩阵放在1行3列的位置sns.heatmap(metrics['confusion_matrix'], annot=True, fmt='d', cmap='Blues', xticklabels=['Not Subscribed', 'Subscribed'], yticklabels=['Not Subscribed', 'Subscribed'], cbar=False)plt.title(f'{model_name} \nAccuracy: {metrics["accuracy"]:.2f}')plt.xlabel('Predicted')plt.ylabel('True')plt.tight_layout()
plt.show()# 2. 绘制ROC曲线
plt.figure(figsize=(8, 6))  # 创建新的图形并设置大小
for model_name, metrics in results.items():plt.plot(metrics['fpr'], metrics['tpr'], label=f'{model_name} (AUC = {metrics["roc_auc"]:.2f})')plt.plot([0, 1], [0, 1], 'k--')
plt.axis([0, 1, 0, 1])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve')
plt.legend()
plt.grid()
plt.show()

针对随机森林使用网格搜索优化

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, auc
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler, PolynomialFeatures
import seaborn as sns# 读取数据
train = pd.read_csv("train.csv")# 列出需要标准化的数值型特征和需要独热编码的类别型特征
numeric_features = ['age', 'duration', 'campaign', 'pdays', 'previous', 'emp_var_rate', 'cons_price_index', 'cons_conf_index', 'lending_rate3m', 'nr_employed']
categorical_features = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome']# 定义ColumnTransformer
preprocessor = ColumnTransformer(transformers=[('poly', PolynomialFeatures(degree=3, include_bias=False), numeric_features),('cat', OneHotEncoder(), categorical_features)])# 定义随机森林模型
rf_model = RandomForestClassifier(random_state=42)# 创建Pipeline
pipeline = Pipeline(steps=[('preprocessor', preprocessor),('classifier', rf_model)])# 分割数据集
X = train.drop('subscribe', axis=1)
y = train["subscribe"].apply(lambda x: 1 if x == "yes" else 0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)# 网格搜索寻找最佳参数
param_grid = {'classifier__n_estimators': [50, 100, 150],'classifier__max_depth': [None, 10, 20, 30],'classifier__min_samples_split': [2, 5, 10],'classifier__min_samples_leaf': [1, 2, 4]
}
grid_search = GridSearchCV(pipeline, param_grid, cv=5, scoring='f1')
grid_search.fit(X_train, y_train)# 获取最佳的模型
best_model = grid_search.best_estimator_
print(f"Best parameters: {grid_search.best_params_}")# 模型评估
y_pred = best_model.predict(X_test)
conf_matrix = confusion_matrix(y_test, y_pred)
report = classification_report(y_test, y_pred)
print(report)# 计算ROC曲线
fpr, tpr, thresholds = roc_curve(y_test, best_model.predict_proba(X_test)[:, 1])
roc_auc = auc(fpr, tpr)# 绘制混淆矩阵和ROC曲线
fig, axes = plt.subplots(1, 2, figsize=(14, 6))# 绘制混淆矩阵
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', ax=axes[0], xticklabels=['Not Subscribed', 'Subscribed'], yticklabels=['Not Subscribed', 'Subscribed'])
axes[0].set_title('Confusion Matrix')
axes[0].set_xlabel('Predicted')
axes[0].set_ylabel('Actual')# 绘制ROC曲线
axes[1].plot(fpr, tpr, color='blue', label=f'ROC curve (area = {roc_auc:.2f})')
axes[1].plot([0, 1], [0, 1], color='red', linestyle='--')
axes[1].set_xlabel('False Positive Rate')
axes[1].set_ylabel('True Positive Rate')
axes[1].set_title('Receiver Operating Characteristic')
axes[1].legend()plt.tight_layout()
plt.show()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/446943.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

每日一刷——10.14——括号匹配(手写栈来实现)

栈与队列题目 第一题 题目 问题描述】设计一个算法判别一个算术表达式的圆括号是否正确配对 【输入形式】一个以为结尾的算术表达式 【输出形式】若配对,则输出圆括号的对数;否则输出no 【样例输入】 (ab)/(cd) 【样例输出】 2 【样例说明】共有两对括…

学习Redisson实现分布式锁

官网&#xff1a;https://redisson.org/ 官方文档&#xff1a;https://redisson.org/docs/getting-started/ 官方中文文档&#xff1a;https://github.com/redisson/redisson/wiki/%E7%9B%AE%E5%BD%95 1、引入依赖 <!--redisson--> <dependency><groupId>or…

【软件工程】数据流图DFD

文章目录 数据流图DFD概述一、数据流图的基本元素二、数据流图的绘制步骤三、数据流图的分层设计四、数据流图的绘制原则五、数据流图的应用 一个完整的数据流包含哪些要素从图中找出所有数据流1. **理解数据流图的结构**2. **识别外部实体**3. **追踪数据流**4. **记录数据流*…

SAP S/4 HANA 销售返利

目录 1 简介 2 后台配置 3 主数据 4 业务操作 4.1 场景 1 - 返利应计 4.2 场景 2 - 最终结算 1 简介 在过去 SAP ECC 把“返利”功能集成在了 SD 模块当中&#xff0c;而 SAP S/4 HANA 把“返利”集成在了结算管理功能模块当中。究其原因&#xff0c;主要是 ECC “返利”…

笔记-stm32移植ucos

文章目录 一、UCOS的基础知识1.1 前后台系统:1.2 RTOS系统可剥夺型内核:前后台系统和RTOS系统 1.3 UCOS系统简介学习方法 二、ucossii移植Step1&#xff1a;在工程中建立存放UCOSS代码的文件夹UCOSIIStep2:向CORE文件夹添加文件Step3:向Config文件夹添加文件Step4:向port文件夹…

本地拉取Docker镜像打包导入远程服务器

起因是因为使用远程服务器拉取镜像时&#xff0c;由于网络问题一直拉不成功&#xff0c;使用国内镜像由于更新不及时&#xff0c;国内镜像没有最新的 docker 镜像。最后使用本地的计算机&#xff0c;通过代理下载最新的镜像后打包成 tar&#xff0c; 然后上传到远程服务器进行导…

electron-vite打包踩坑记录

electron-vite打包踩坑记录 大前端已成趋势&#xff0c;用electron开发桌面端应用越来越普遍 近期尝试用electronvite开发了个桌面应用&#xff0c;electron-vite地址&#xff0c;可用使用vue开发&#xff0c;vite打包&#xff0c;这样就很方便了 但是&#xff0c;我尝试了一…

【机器学习】并行计算(parallel computation)Part1

为什么我们在机器学习中需要用到并行计算呢&#xff0c;因为现在最流行的机器学习算法都是神经网络&#xff0c;神经网络模型的计算量、参数量都很大&#xff0c;比如ResNet-50参数量为25M。而我们在训练的时候使用的数据集也很大&#xff0c;比如ImageNet数据集含有14M张图片。…

FileInputStream类

目录 1.案例代码&#xff1a; 2.注意细节 3.FileInputStream循环读取 1.案例代码&#xff1a; 准备的txt文件 结果&#xff1a; 如果需要输出原本的字母&#xff0c;强制转换为char即可&#xff1a; 结果&#xff1a; 2.注意细节 &#xff08;1&#xff09;如果文件不存在…

Qt和c++面试集合

目录 Qt面试 什么是信号&#xff08;Signal&#xff09;和槽&#xff08;Slot&#xff09;&#xff1f; 什么是Meta-Object系统&#xff1f; 什么是Qt的MVC模式&#xff1f; 1. QT中connect函数的第五个参数是什么&#xff1f;有什么作用&#xff1f; 3. 在QT中&#xff…

【NestJS入门到精通】装饰器

目录 方法装饰器通过prototype添加属性、方法 属性装饰器拓展 方法装饰器参数装饰器 方法装饰器 ClassDecorator 定义了一个类装饰器 a&#xff0c;并将其应用于类 A。装饰器 a 会在类 A 被定义时执行。 const a:ClassDecorator (target:any)>{console.log(target,targe…

概率 多维随机变量与分布

一、二维 1、二维随机变量及其分布 假设E是随机试验&#xff0c;Ω是样本空间&#xff0c;X、Y是Ω的两个变量&#xff1b;(X,Y)就叫做二维随机变量或二维随机向量。X、Y来自同一个样本空间。 联合分布函数 F(x,y)P(X≤x,Y≤y)&#xff0c;即F(x,y)表示求(x,y)左下方的面积。 …

Struct Streaming

spark进行实时数据流计算时有两个工具 Spark Streaming:编写rdd代码处理数据流,可以解决非结构化的流式数据 Structured Streaming:编写df代码处理数据流,可以解决结构化和半结构化的流式数据 实时计算 实时计算&#xff0c;通常也称为“实时流计算”、“流式计算” 流数据处…

Unity3d使用JsonUtility.FromJson读取json文件

使用JsonUtility.FromJson方法不需要额外引用第三方库。该方法只能读取json对象&#xff0c;而不能读取json数组。 假如我们有如下的json数组&#xff1a; [ {"id":1, "name":"first2021", "level":5, "score":100, "…

vue3 对 vue2 有什么优势

1、diff算法的优化--静态标记&#xff08;PatchFlag&#xff09; vue2中的虚拟dom是全量的对比&#xff08;每个节点不论写死的还是动态的都会一层一层比较&#xff0c;这就浪费了大部分事件在对比静态节点上&#xff09; vue3编译模板时&#xff0c;动态节点做标记 标记分为不…

仿函数(函数对象)

0.含义 仿函数和函数对象在C中含义一致。官方解释是&#xff1a; &#xff08;&#xff09;就是函数调用运算符&#xff0c;也就是说一个类重载了小括号&#xff0c;它实例化的对象就可以像函数一样使用。 “仿”函数&#xff0c;意味着它和函数使用有相同点&#xff1a; …

盘点双十一四款不错的品牌好物!2024学生党高颜值平价好物推荐!

在双十一这个购物狂欢节&#xff0c;不少学生党都希望以最实惠的价格买到心仪的商品。今天&#xff0c;我们就来盘点四款双十一期间值得入手的高颜值平价好物&#xff0c;让同学们在享受优惠的同时&#xff0c;也能拥有品质生活&#xff01; 品牌好物一、希亦CG超声波清洗机 双…

数据中心物理安全的历史和演变

在当今的数字时代&#xff0c;数据中心托管已成为我们互联世界的支柱。这些设施在存储、管理和处理我们日常生活所需的大量信息方面发挥着至关重要的作用。从社交媒体平台和电子商务网站到流媒体服务和云计算&#xff0c;数据中心为我们依赖的数字服务提供支持。 随着企业越来…

Swarm 框架登场:OpenAI 第 3 阶段「敲门砖」;马斯克的 Teslabot 实际有人远程操控丨 RTE 开发者日报

开发者朋友们大家好&#xff1a; 这里是 「RTE 开发者日报」 &#xff0c;每天和大家一起看新闻、聊八卦。我们的社区编辑团队会整理分享 RTE&#xff08;Real-Time Engagement&#xff09; 领域内「有话题的 新闻 」、「有态度的 观点 」、「有意思的 数据 」、「有思考的 文…

音视频开发:FFmpeg库的使用

文章目录 一、FFmpeg的介绍二、FFmpeg的安装三、FFmpeg的使用1.ffplay&#xff1a;播放音视频2.ffprobe&#xff1a;查看视频信息3.ffmpeg&#xff1a;处理视频(1)格式转换(2)帮助 四、参考资料 一、FFmpeg的介绍 FFmpeg 是使用广泛的多媒体框架&#xff0c;是一个强大的音视频…