要查看Python中的决策树模型,你可以使用以下方法:
可视化决策树
使用`Graphviz`库可以将决策树模型可视化,这有助于分析和调整模型。你可以使用`dot`命令和`pydotplus`库来绘制决策树。
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from pydotplus import graph_from_dot_data
from IPython.display import Image
import pydot
加载数据集
iris = load_iris()
X = iris.data
y = iris.target
划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
创建决策树模型
model = DecisionTreeClassifier(random_state=0)
model.fit(X_train, y_train)
预测
predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
可视化决策树
dot_data = tree.export_graphviz(model, out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True,
special_characters=True)
graph = graph_from_dot_data(dot_data)
Image(graph.create_png())
查看决策树结构
你可以通过`DecisionTreeClassifier`对象的`tree_`属性来查看决策树的结构。
查看决策树结构
print(model.tree_.__str__())
使用其他库
除了`pydotplus`,你还可以使用`sklearn`自带的`export_graphviz`函数来导出决策树的可视化数据,然后用其他可视化工具(如`graphviz`命令行工具)来生成图像。
from sklearn.tree import export_graphviz
导出决策树为DOT格式
dot_data = export_graphviz(model, out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True,
special_characters=True)
使用graphviz命令行工具生成图像
dot -Tpng tree.dot -o tree.png
以上方法可以帮助你查看和理解Python中的决策树模型。