声明:
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()



