对红酒数据集,分别采用决策树算法和随机森林算法进行分类。

1.导入所需要的包

python 复制代码
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split

2.导入数据,并且对随机森林和决策数进行对比

python 复制代码
x_train,x_test,y_train,y_test=train_test_split(wine.data,wine.target,test_size=0.3)
clf=DecisionTreeClassifier(random_state=0)
rfc=RandomForestClassifier(random_state=0)
clf=clf.fit(x_train,y_train)
rfc=rfc.fit(x_train,y_train)
score_c=clf.score(x_test,y_test)
score_r=rfc.score(x_test,y_test)
print(score_c,score_r)

运行结果:

0.8703703703703703 0.9259259259259259

3.数据可视化

python 复制代码
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
import matplotlib.pyplot as plt
%matplotlib inline
wine=load_wine()
rfc=RandomForestClassifier(n_estimators=25)
rfc_s=cross_val_score(rfc,wine.data,wine.target,cv=10)
clf=DecisionTreeClassifier()
clf_s=cross_val_score(clf,wine.data,wine.target,cv=10)
plt.plot(range(1,11),rfc_s,label='RandomForest')
plt.plot(range(1,11),clf_s,label='DecisionTree')
plt.legend()
plt.show()

运行结果:

相关推荐
smj2302_7968265243 分钟前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
cynicme1 小时前
力扣3531——统计被覆盖的建筑
算法·leetcode
core5122 小时前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.8242 小时前
计数if|
算法
a伊雪2 小时前
c++ 引用参数
c++·算法
Data_agent3 小时前
1688获得1688店铺列表API,python请求示例
开发语言·python·算法
2301_764441333 小时前
使用python构建的应急物资代储博弈模型
开发语言·python·算法
hetao17338374 小时前
2025-12-11 hetao1733837的刷题笔记
c++·笔记·算法
Xの哲學4 小时前
Linux电源管理深度剖析
linux·服务器·算法·架构·边缘计算
小飞Coding4 小时前
一文讲透 TF-IDF:如何用一个向量“代表”一篇文章?
算法