随机森林和交叉验证 一、随机森林随机森林是一种集成学习算法Ensemble Learning主要用于分类和回归任务。简单来说随机森林 多棵决策树 投票/平均1、随机森林的构成随机森林主要由两部分组成 (1). 决策树Decision Tree 每棵树都是一个分类器。邮件||--是否包含免费|||是|||是否大量包含链接|||是|||垃圾邮件(2). 多棵树组合 随机森林生成很多棵决策树随机森林 树1→ 垃圾邮件 树2→ 垃圾邮件 树3→ 正常邮件 树4→ 垃圾邮件 树5→ 垃圾邮件 最终 垃圾邮件2、随机森林分类流程(1)划分数据xtrain,xtest,ytrain,ytest\ train_test_split(x,y,test_size0.2,random_state100)(2)、SMOTE处理类别不平衡oversamplerSMOTE(random_state0)#创建 SMOTE 对象os_x_train,os_y_trainoversampler.fit_resample(xtrain,ytrain)使用 SMOTE 方法解决训练集中类别不平衡问题。 (3)、创建随机森林rfRandomForestClassifier(n_estimators100,max_features0.8,random_state0)n_estimators100表示建立100个树 max_features0.8表示每次分裂随机使用80%的特征 random_state0随机种子 (4)、训练模型rf.fit(os_x_train,os_y_train)(5)预测train_predictedrf.predict(xtrain)#训练集test_predictedrf.predict(xtest)#测试机代码展示importpandasaspdimportmatplotlib.pyplotaspltfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierfromsklearn.metricsimportconfusion_matrix,classification_reportfromimblearn.over_samplingimportSMOTE# # 绘制混淆矩阵函数# defcm_plot(y_true,y_pred):cmconfusion_matrix(y_true,y_pred)plt.matshow(cm,cmapplt.cm.Blues)plt.colorbar()foriinrange(len(cm)):forjinrange(len(cm)):plt.annotate(cm[i,j],xy(j,i),horizontalalignmentcenter,verticalalignmentcenter)plt.ylabel(True label)plt.xlabel(Predicted label)returnplt# # 1.读取数据# dfpd.read_csv(spambase.csv)# 特征Xdf.iloc[:,:-1]# 标签ydf.iloc[:,-1]# # 2.划分训练集和测试集# X_train,X_test,y_train,y_testtrain_test_split(X,y,test_size0.2,random_state100)# # 3.SMOTE处理样本不平衡# smoteSMOTE(random_state0)X_train_smote,y_train_smotesmote.fit_resample(X_train,y_train)# # 4.建立随机森林模型# rfRandomForestClassifier(n_estimators100,max_features0.8,random_state0)# 训练rf.fit(X_train_smote,y_train_smote)# # 5.训练集预测# train_predrf.predict(X_train)print(训练集结果)print(classification_report(y_train,train_pred,digits4))# 混淆矩阵cm_plot(y_train,train_pred).show()# # 6.测试集预测# test_predrf.predict(X_test)print(测试集结果)print(classification_report(y_test,test_pred,digits4))# 测试集混淆矩阵cm_plot(y_test,test_pred).show()# # 7.特征重要性分析# # 获取特征重要性importancesrf.feature_importances_ importance_dfpd.DataFrame({feature:X.columns,importance:importances})# 排名前10importance_dfimportance_df.sort_values(byimportance,ascendingFalse).head(10)# 绘制柱状图plt.figure(figsize(8,5))plt.barh(importance_df[feature],importance_df[importance])plt.xlabel(Importance)plt.ylabel(Feature)plt.title(Top 10 Feature Importance)plt.gca().invert_yaxis()plt.show()

相关新闻

最新新闻

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现 【免费下载链接】serenity The Serenity Operating System 🐞 项目地址: https://gitcode.com/GitHub_Trending/se/serenity 导读 本文以 getopt(3) 手册 为核心&a…

2026/10/1 19:32:24
轻量服务器还是ECS?大促云服务器选购与避坑实战指南

轻量服务器还是ECS?大促云服务器选购与避坑实战指南

每年大促节点,群里永远有人在问同一个问题:“38元的轻量服务器到底怎么抢?为什么我每次点进去都是已售罄?68元直购和99元的ECS我到底选哪个?”作为一个常年帮团队和自己采购云服务器的老用户,我太清楚这种纠…

2026/9/30 21:32:07
为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南 【免费下载链接】agents Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity 项目地址:…

2026/10/2 15:29:32
PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署 【免费下载链接】PaddleOCR Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between i…

2026/10/3 7:41:27
Spring源码解析:构造器注入的类型转换与候选匹配机制

Spring源码解析:构造器注入的类型转换与候选匹配机制

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/1 19:32:35
openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由 【免费下载链接】openai-agents-python A lightweight, powerful framework for multi-agent workflows 项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-pyth…

2026/9/30 21:32:11

日新闻

周新闻

月新闻