Python之随机森林实战
2024-10-14 19:27:24
代码实现:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 4 09:38:57 2018 @author: zhen
""" from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt iris = load_iris()
x = iris.data[:, :2]
y = iris.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42) # n_estimators:森林中树的个数(默认为10),建议为奇数
# n_jobs:并行执行任务的个数(包括模型训练和预测),默认值为-1,表示根据核数
21 rnd_clf = RandomForestClassifier(n_estimators=15, max_leaf_nodes=16, n_jobs=1)
22 rnd_clf.fit(x_train, y_train)
23
24 y_predict_rf = rnd_clf.predict(x_test) print(accuracy_score(y_test, y_predict_rf)) for name, score in zip(iris['feature_names'], rnd_clf.feature_importances_):
print(name, score) # 可视化
plt.plot(x_test[:, 0], y_test, 'r.', label='real')
plt.plot(x_test[:, 0], y_predict_rf, 'b.', label='predict')
plt.xlabel('sepal-length', fontsize=15)
plt.ylabel('type', fontsize=15)
plt.legend(loc="upper left")
plt.show() plt.plot(x_test[:, 1], y_test, 'r.', label='real')
plt.plot(x_test[:, 1], y_predict_rf, 'b.', label='predict')
plt.xlabel('sepal-width', fontsize=15)
plt.ylabel('type', fontsize=15)
plt.legend(loc="upper right")
plt.show()
结果:
可视化(查看每个预测条件的影响):
分析:鸢尾花的花萼长度在小于6时预测准确率很高,随着长度的增加,在6~7这段中,预测出现较大错误率,当大于7时,预测会恢复到较好的情况。宽度也出现类似的情况,在3~3.5这个范围出现较高错误,因此在训练中建议在训练数据中适量增加中间部分数据的训练量(该部分不容易区分),以便得到较好的训练模型!
最新文章
- iOS 开发技术牛人博客
- js下载浏览器中的图片
- SpringMVC框架下实现JSON(类方法中回传数据到jsp页面,使用jQuery方法回传)
- ES6 学习笔记(1)
- atitit. web 在线文件管理器最佳实践(1)--- elFinder 的使用流程解决之道 。打开浏览服务器文件夹java .net php
- 【转】linux dumpe2fs命令
- bzoj1391 最大权闭合子图(also最小割、网络流)
- MySQL数据库服务器 主从配置
- 用js 将long类型转换成日期格式
- [BZOJ3675]序列分割
- Shader 入门笔记(三) ShaderLab 初识
- 怎么动态生成js变量
- adb 常用命令-转载
- SQL 语句 写法
- XML解析之XPath
- mysql触发器使用方法具体解释
- [LeetCode]Letter Combinations of a Phone Number题解
- (杭电1019 最小公倍数) Least Common Multiple
- EXT4+Struts2 JSON的问题
- Zabbix分布式监控
热门文章
- python 开发环境配置
- 1-VScode格式化ESlint-方法(最全最好用方法!)
- 【sping揭秘】19、关于spring中jdbctemplate中的DataSource怎么来呢
- 纯JavaScript实现俄罗斯方块(详细注释,ES6)
- 微服务开发有道之把项目迁移到Kubernetes上的5个小技巧
- 使用POI导出Excel文件
- Linux内核源码分析之调度、内核线程模型 And Centos7.2's Kernel Resource Analysis
- 在Windows环境中安装Neo4j
- RecyclerView的简单使用
- 从零开始学 Web 之 jQuery(二)获取和操作元素的属性