栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【练习/sklearn库基础】使用分类决策树、回归决策树、分类随机森林、回归随机森林进行分类预测,条形图的形式显示评估结果

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【练习/sklearn库基础】使用分类决策树、回归决策树、分类随机森林、回归随机森林进行分类预测,条形图的形式显示评估结果

声明:
1、 学生刚开始学习python,代码会有很多不严谨,也较为粗糙,单纯用于广大网友参考,希望能起到一定的帮助
2、 如果要转载,请标记出来源
3、本文纯粹用于技术练习,请勿用作非法途径
4、如果有问题请在评论区指出,虚心接受立马改正
做题途中所遇问题:

代码块:

#2、 导入sklearn库自带的乳腺癌数据集(load_breast_cancer),
# 使用分类决策树、回归决策树、分类随机森林、回归随机森林进行分类预测,
# 并使用score()方法评估4种算法的性能,并以可视化图形(条形图)的形式显示评估结果
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
#中文
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False

#共同内容
diabetes=load_breast_cancer()
X=diabetes.data
Y=diabetes.target
x_train,x_test,y_train,y_test=train_test_split(X, Y, test_size=0.2)
#存放评估结果分数
model_result=[]
#分类决策树
tree1=DecisionTreeClassifier(criterion='entropy',min_samples_leaf=3)
tree1.fit(x_train,y_train)
y_pred=tree1.predict(x_test)
print("预测值:n",y_pred)
#结果评估
score1=tree1.score(x_test,y_test)
print("DecisionTreeClassifier模型评估结果:%.2f"% score1)
model_result.append(score1)
#回归决策树
tree2=DecisionTreeRegressor()
tree2.fit(x_train,y_train)
y_pred=tree2.predict(x_test)
print("预测值:n",y_pred)
#结果评估
score2=tree2.score(x_test,y_test)
print("DecisionTreeRegressor模型评估结果:%.2f"% score2)
model_result.append(score2)
#分类随机森林
tree3=RandomForestClassifier()
tree3.fit(x_train,y_train)
y_pred=tree3.predict(x_test)
print("预测值:n",y_pred)
#结果评估
score3=tree3.score(x_test,y_test)
print("DecisionTreeRegressor模型评估结果:%.2f"% score3)
model_result.append(score3)
#回归随机森林
tree4=RandomForestRegressor()
tree4.fit(x_train,y_train)
y_pred=tree4.predict(x_test)
print("预测值:n",y_pred)
#结果评估
score4=tree4.score(x_test,y_test)
print("DecisionTreeRegressor模型评估结果:%.2f"% score4)
model_result.append(score4)

#绘图
names=["分类决策树","回归决策树","分类随机森林","回归随机森林"]
figure=plt.figure()
plt.xlabel("方法")
plt.ylabel("评估结果评分")
a=plt.bar(names,model_result,fc='y')
#定义函数来显示柱状数值
x=range(0,len(names))
for i in a:
   height=i.get_height()
   plt.text(i.get_x()+i.get_width()/2.-0.2,1.03*height,'%.2f'%float(height))
plt.show()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/649492.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号