关于葡萄酒品质决策树和随机森林两种算法对比代码分析
时间: 2023-06-30 08:05:00 浏览: 119
两种算法的代码实现差别不大,主要区别在于使用的模型不同。下面是简单的代码分析和对比:
决策树:
```python
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 导入数据
data = pd.read_csv('winequality.csv')
# 将数据分为特征和标签
X = data.drop('quality', axis=1)
y = data['quality']
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义模型
model = DecisionTreeClassifier()
# 拟合模型
model.fit(X_train, y_train)
# 预测结果
y_pred = model.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
随机森林:
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 导入数据
data = pd.read_csv('winequality.csv')
# 将数据分为特征和标签
X = data.drop('quality', axis=1)
y = data['quality']
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义模型
model = RandomForestClassifier()
# 拟合模型
model.fit(X_train, y_train)
# 预测结果
y_pred = model.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
从代码实现来看,随机森林与决策树的主要区别在于模型的定义不同。随机森林使用的是`RandomForestClassifier`,而决策树使用的是`DecisionTreeClassifier`。在其他方面,两种算法的实现基本相同。
阅读全文