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

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()

运行结果:

相关推荐
铭哥的编程日记2 分钟前
深入浅出蓝桥杯:算法基础概念与实战应用(三)搜索
算法·蓝桥杯·深度优先
2501_941111894 分钟前
低延迟系统C++优化
开发语言·c++·算法
2501_941111991 小时前
C++中的装饰器模式变体
开发语言·c++·算法
Espresso Macchiato1 小时前
Leetcode 3748. Count Stable Subarrays
算法·leetcode·职场和发展·leetcode hard·leetcode 3748·leetcode周赛476·区间求和
大袁同学2 小时前
【哈希hash】:程序的“魔法索引”,实现数据瞬移
数据结构·c++·算法·哈希算法·散列表
一水鉴天2 小时前
整体设计 全面梳理复盘 之39 生态工具链 到顶级表征及其完全公理化
大数据·人工智能·算法
Moonbit2 小时前
入围名单公布|2025 MGPIC 决赛即将拉开帷幕!
后端·算法
2501_941112612 小时前
C++与Docker集成开发
开发语言·c++·算法
智者知已应修善业2 小时前
【51单片机:两边向中间流水:即两边先点亮然后熄灭,次边的点亮再熄灭,直到最中间的两个点亮再熄灭,然后重复动作。】2023-3-4
c语言·c++·经验分享·笔记·嵌入式硬件·算法·51单片机