基于决策树实现葡萄酒分类代码
时间: 2024-10-11 16:04:41 浏览: 45
基于决策树实现葡萄酒分类通常涉及以下几个步骤,这里我会给出一个简化的Python示例,使用sklearn库中的`DecisionTreeClassifier`:
```python
# 导入所需的库
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 加载葡萄酒数据集(Iris数据集的一个版本)
wine = datasets.load_wine()
X = wine.data # 特征矩阵
y = wine.target # 类别标签
# 数据预处理,如归一化或编码类别
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建决策树分类器
clf = DecisionTreeClassifier()
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 计算预测准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
# 如果需要,可以查看决策树的可视化结果:
# from sklearn.tree import export_graphviz
# export_graphviz(clf, out_file="wine_tree.dot", feature_names=wine.feature_names, class_names=wine.target_names)
#
阅读全文