scikit-learn中用gridsearchcv给随机森林(RF)自动调参

2024-03-15 16:58

本文主要是介绍scikit-learn中用gridsearchcv给随机森林(RF)自动调参,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

全文参考 1:http://scikit-learn.org/stable/auto_examples/model_selection/grid_search_digits.html#parameter-estimation-using-grid-search-with-cross-validation

全文参考 2:http://scikit-learn.org/stable/modules/model_evaluation.html#the-scoring-parameter-defining-model-evaluation-rules

全文参考 3:http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html#sklearn.metrics.roc_auc_score

全文参考 4:http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html#sphx-glr-auto-examples-model-selection-plot-roc-py

实验重点:随机森林(RandomForest) + 5折交叉验证(Cross-Validation) + 网格参数寻优(GridSearchCV) + 二分类问题中ROC曲线的绘制。

由于原始数据本身质量很好,且正负样本基本均衡,没有做数据预处理工作。

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from sklearn.metrics import roc_curve
  5. from sklearn.metrics import roc_auc_score
  6. from sklearn.metrics import classification_report
  7. from sklearn.model_selection import GridSearchCV
  8. from sklearn.ensemble import RandomForestClassifier

  1. #导入数据,来源于:http://mldata.org/repository/tags/data/IDA_Benchmark_Repository/,见上图
  2. dataset = pd.read_csv('image_data.csv', header=None, encoding='utf-8')
  3. dataset_positive = dataset[dataset[0] == 1.0]
  4. dataset_negative = dataset[dataset[0] == -1.0]
  5. #训练集和测试集按照7:3分割,分割时兼顾正负样本所占比例
  6. #其中训练集基于5折交叉验证做网格搜索找出最优参数,应用于测试集以评价算法性能
  7. train_dataset = pd.concat([dataset_positive[0:832], dataset_negative[0:628]])
  8. train_recon = train_dataset.sort_index(axis=0, ascending=True)
  9. test_dataset = pd.concat([dataset_positive[832:1188], dataset_negative[628:898]])
  10. test_recon = test_dataset.sort_index(axis=0, ascending=True)
  11. y_train = np.array(train_recon[0])
  12. X_train = np.array(train_recon.drop([0], axis=1))
  13. y_test = np.array(test_recon[0])
  14. X_test = np.array(test_recon.drop([0], axis=1))

  1. # Set the parameters by cross-validation
  2. parameter_space = {
  3. "n_estimators": [10, 15, 20],
  4. "criterion": ["gini", "entropy"],
  5. "min_samples_leaf": [2, 4, 6],
  6. }
  7. #scores = ['precision', 'recall', 'roc_auc']
  8. scores = ['roc_auc']
  9. for score in scores:
  10. print("# Tuning hyper-parameters for %s" % score)
  11. print()
  12. clf = RandomForestClassifier(random_state=14)
  13. grid = GridSearchCV(clf, parameter_space, cv=5, scoring='%s' % score)
  14. #scoring='%s_macro' % score:precision_macro、recall_macro是用于multiclass/multilabel任务的
  15. grid.fit(X_train, y_train)
  16. print("Best parameters set found on development set:")
  17. print()
  18. print(grid.best_params_)
  19. print()
  20. print("Grid scores on development set:")
  21. print()
  22. means = grid.cv_results_['mean_test_score']
  23. stds = grid.cv_results_['std_test_score']
  24. for mean, std, params in zip(means, stds, grid.cv_results_['params']):
  25. print("%0.3f (+/-%0.03f) for %r"
  26. % (mean, std * 2, params))
  27. print()
  28. print("Detailed classification report:")
  29. print()
  30. print("The model is trained on the full development set.")
  31. print("The scores are computed on the full evaluation set.")
  32. print()
  33. bclf = grid.best_estimator_
  34. bclf.fit(X_train, y_train)
  35. y_true = y_test
  36. y_pred = bclf.predict(X_test)
  37. y_pred_pro = bclf.predict_proba(X_test)
  38. y_scores = pd.DataFrame(y_pred_pro, columns=bclf.classes_.tolist())[1].values
  39. print(classification_report(y_true, y_pred))
  40. auc_value = roc_auc_score(y_true, y_scores)

输出结果:


  1. #绘制ROC曲线
  2. fpr, tpr, thresholds = roc_curve(y_true, y_scores, pos_label=1.0)
  3. plt.figure()
  4. lw = 2
  5. plt.plot(fpr, tpr, color='darkorange', linewidth=lw, label='ROC curve (area = %0.4f)' % auc_value)
  6. plt.plot([0, 1], [0, 1], color='navy', linewidth=lw, linestyle='--')
  7. plt.xlim([0.0, 1.0])
  8. plt.ylim([0.0, 1.05])
  9. plt.xlabel('False Positive Rate')
  10. plt.ylabel('True Positive Rate')
  11. plt.title('Receiver operating characteristic example')
  12. plt.legend(loc="lower right")
  13. plt.show()




转自: https://blog.csdn.net/lixiaowang_327/article/details/53434744

这篇关于scikit-learn中用gridsearchcv给随机森林(RF)自动调参的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/812643

相关文章

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

MyBatis-Plus 自动赋值实体字段最佳实践指南

《MyBatis-Plus自动赋值实体字段最佳实践指南》MyBatis-Plus通过@TableField注解与填充策略,实现时间戳、用户信息、逻辑删除等字段的自动填充,减少手动赋值,提升开发效率与... 目录1. MyBATis-Plus 自动赋值概述1.1 适用场景1.2 自动填充的原理1.3 填充策略

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis