用Python实现用决策树分类红酒数据集
时间: 2024-11-10 15:14:13 浏览: 4
在Python中,我们可以使用scikit-learn库来构建决策树分类红酒数据集。假设你已经有了一个名为`wine_data.csv`的CSV文件,包含了红酒的各种属性作为特征,以及一个标签列作为类别。以下是使用sklearn的简单示例:
```python
# 导入所需的库
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 加载数据
data = pd.read_csv('wine_data.csv')
# 定义特征和目标变量
X = data.drop('target', axis=1) # 特征
y = data['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)
# 可视化决策树
import graphviz
dot_data = tree.export_graphviz(clf, out_file=None,
feature_names=X.columns,
class_names=data.target.unique(),
filled=True, rounded=True,
special_characters=True)
graph = graphviz.Source(dot_data)
graph.view()
阅读全文