jupyter notebook决策树代码实现
时间: 2024-06-17 14:01:56 浏览: 133
python jupyter notebook房价预测完整案例
5星 · 资源好评率100%
Jupyter Notebook是一个交互式的笔记本环境,常用于数据科学和机器学习项目。使用Python的scikit-learn库可以轻松实现决策树。以下是一个简单的决策树模型在Jupyter Notebook中的代码示例:
```python
# 导入必要的库
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 假设你有一个名为'data.csv'的数据集
data = pd.read_csv('data.csv')
# 数据预处理(这里假设X是特征,y是目标变量)
X = data.drop('target_column', axis=1)
y = data['target_column']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建并训练决策树模型
tree_model = DecisionTreeClassifier()
tree_model.fit(X_train, y_train)
# 预测测试集
y_pred = tree_model.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
# 可视化决策树(如果使用的是`graphviz`库)
try:
from sklearn.tree import export_graphviz
import graphviz
dot_data = export_graphviz(tree_model, out_file=None,
feature_names=X.columns,
class_names=y.unique(),
filled=True, rounded=True,
special_characters=True)
graph = graphviz.Source(dot_data)
graph.view()
except ImportError:
print("Graphviz is not installed, so tree visualization is not possible.")
```
阅读全文