Câu hỏi đầu tiên: Vâng, logic của bạn là chính xác. Nút bên trái là True và nút bên phải là False. Điều này phản trực giác; true nói chung sẽ có nghĩa là một giá trị nhỏ hơn.
Câu hỏi thứ hai: Vấn đề này được giải quyết tốt nhất bằng cách trực quan hóa cây dưới dạng đồ thị với pydotplus. Thuộc tính 'class_names' của tree.export_graphviz() sẽ thêm một khai báo lớp vào lớp đa số của mỗi nút. Mã được thực hiện trong iPython.
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf2 = tree.DecisionTreeClassifier()
clf2 = clf2.fit(iris.data, iris.target)
with open("iris.dot", 'w') as f:
f = tree.export_graphviz(clf, out_file=f)
import os
os.unlink('iris.dot')
import pydotplus
dot_data = tree.export_graphviz(clf2, out_file=None)
graph2 = pydotplus.graph_from_dot_data(dot_data)
graph2.write_pdf("iris.pdf")
from IPython.display import Image
dot_data = tree.export_graphviz(clf2, out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True, # leaves_parallel=True,
special_characters=True)
graph2 = pydotplus.graph_from_dot_data(dot_data)
## Color of nodes
nodes = graph2.get_node_list()
for node in nodes:
if node.get_label():
values = [int(ii) for ii in node.get_label().split('value = [')[1].split(']')[0].split(',')];
color = {0: [255,255,224], 1: [255,224,255], 2: [224,255,255],}
values = color[values.index(max(values))]; # print(values)
color = '#{:02x}{:02x}{:02x}'.format(values[0], values[1], values[2]); # print(color)
node.set_fillcolor(color)
#
Image(graph2.create_png())
Đối với việc xác định lớp nhìn vào chiếc lá, ví dụ bạn không có lá với một lớp duy nhất, như các thiết lập iris dữ liệu nào. Điều này là phổ biến và có thể yêu cầu mô hình quá phù hợp để đạt được kết quả như vậy. Phân phối các lớp riêng biệt là kết quả tốt nhất cho nhiều mô hình được xác thực chéo.
Tận hưởng mã!
Ngoài sự tò mò, bạn đã vẽ cây quyết định như thế nào? – Matt
Xuất lần đầu tiên cây sang định dạng JSON (xem [link] này (http://www.garysieling.com/blog/rending-scikit-decision-trees-d3-js)) và sau đó vẽ cây bằng cách sử dụng d3.js . Hoặc bạn có thể trực tiếp sử dụng hàm được nhúng: 'tree.export_graphviz (clf, out_file = your_out_file, feature_names = your_feature_names)' Hy vọng nó hoạt động, @Matt –