Hướng dẫn how do you print decision tree rules in python? - làm thế nào để bạn in quy tắc cây quyết định trong python?

Các quy tắc trích xuất từ ​​cây quyết định có thể giúp hiểu rõ hơn về cách các mẫu lan truyền qua cây trong quá trình dự đoán. Có thể cần thiết nếu chúng ta muốn thực hiện một cây quyết định mà không cần Scikit hoặc khác với ngôn ngữ Python. Cây quyết định dễ dàng chuyển sang bất kỳ ngôn ngữ lập trình nào vì có tập hợp các câu lệnh

# get the text representation
text_representation = tree.export_text[clf]
print[text_representation]
2. Tôi đã thấy nhiều ví dụ về việc di chuyển các cây quyết định Scikit-learn vào C, C ++, Java hoặc thậm chí là SQL.

Trong bài đăng này, tôi sẽ chỉ cho bạn 3 cách để có được các quy tắc quyết định từ cây quyết định [cho cả hai nhiệm vụ phân loại và hồi quy] với các phương pháp sau:

  • Đại diện văn bản tích hợp,
  • Chuyển đổi cây quyết định thành mã [có thể bằng bất kỳ ngôn ngữ lập trình nào]
  • Chuyển đổi một cây quyết định thành bộ các quy tắc có thể đọc được của con người [cách tiếp cận yêu thích của tôi]set of rules which are human-readable [my favourite approach]

Nếu bạn muốn hình dung mô hình cây quyết định của mình, thì bạn sẽ thấy bài viết của tôi trực quan hóa cây quyết định theo 4 cách với Scikit-learn và Python

Nếu bạn muốn đào tạo cây quyết định và các thuật toán ML khác [rừng ngẫu nhiên, mạng thần kinh, XGBOOST, CATBOOST, LIGHGBM] theo cách tự động, bạn nên kiểm tra gói Python tự động nguồn mở của chúng tôi trên Github: MLJAR-Supervised

Đào tạo cây quyết định về nhiệm vụ phân loại

Hãy để đào tạo một

# get the text representation
text_representation = tree.export_text[clf]
print[text_representation]
3 trên bộ dữ liệu
# get the text representation
text_representation = tree.export_text[clf]
print[text_representation]
4. Tôi sẽ sử dụng các tham số siêu mặc định cho trình phân loại, ngoại trừ
# get the text representation
text_representation = tree.export_text[clf]
print[text_representation]
5 [don lồng muốn cây quá sâu, vì lý do dễ đọc].

from matplotlib import pyplot as plt
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier 
from sklearn import tree

# Prepare the data data
iris = datasets.load_iris[]
X = iris.data
y = iris.target

# Fit the classifier with max_depth=3
clf = DecisionTreeClassifier[max_depth=3, random_state=1234]
model = clf.fit[X, y]

Đại diện văn bản tích hợp của Scikit-learn

Lớp cây quyết định Scikit-learn có

# get the text representation
text_representation = tree.export_text[clf]
print[text_representation]
6. Nó trả về biểu diễn văn bản của các quy tắc.

# get the text representation
text_representation = tree.export_text[clf]
print[text_representation]

Đầu ra:

|--- feature_2   2.45
|   |--- feature_3   1.75
|   |   |--- feature_2   4.85
|   |   |   |--- class: 2

Bạn có thể chuyển tên tính năng làm đối số để có được biểu diễn văn bản tốt hơn:

text_representation = tree.export_text[clf, feature_names=iris.feature_names]
print[text_representation]

Đầu ra, với tên tính năng của chúng tôi thay vì chung

# get the text representation
text_representation = tree.export_text[clf]
print[text_representation]
7,
# get the text representation
text_representation = tree.export_text[clf]
print[text_representation]
8, trên mạng:

|--- petal length [cm]   2.45
|   |--- petal width [cm]   1.75
|   |   |--- petal length [cm]   4.85
|   |   |   |--- class: 2

Có bất kỳ phương pháp tích hợp nào để trích xuất các quy tắc mã

# get the text representation
text_representation = tree.export_text[clf]
print[text_representation]
2 từ cây scikit-learn. Chúng ta cần viết nó. Mã dưới đây dựa trên câu trả lời của StackoverFlow - được cập nhật lên Python 3.

from sklearn.tree import _tree

def tree_to_code[tree, feature_names]:
    tree_ = tree.tree_
    feature_name = [
        feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
        for i in tree_.feature
    ]
    feature_names = [f.replace[" ", "_"][:-5] for f in feature_names]
    print["def predict[{}]:".format[", ".join[feature_names]]]

    def recurse[node, depth]:
        indent = "    " * depth
        if tree_.feature[node] != _tree.TREE_UNDEFINED:
            name = feature_name[node]
            threshold = tree_.threshold[node]
            print["{}if {}  {}".format[indent, name, np.round[threshold,2]]]
            recurse[tree_.children_right[node], depth + 1]
        else:
            print["{}return {}".format[indent, tree_.value[node]]]

    recurse[0, 1]

Mã trên đi bộ qua các nút trong cây và in ra các quy tắc quyết định. Các quy tắc được trình bày dưới dạng chức năng Python. Mã dưới đây được tạo bằng

|--- feature_2   2.45
|   |--- feature_3   1.75
|   |   |--- feature_2   4.85
|   |   |   |--- class: 2
1. Bạn có thể dễ dàng điều chỉnh mã trên để tạo ra các quy tắc quyết định trong bất kỳ ngôn ngữ lập trình nào.

def predict[sepal_length, sepal_width, petal_length, petal_width]:
    if petal length [cm]  2.45
        if petal width [cm]  1.75
            if petal length [cm]  4.85
                return [[ 0.  0. 43.]]

Các quy tắc mã từ ví dụ trước đó khá thân thiện với máy tính so với thân thiện với con người. Hãy để cập nhật mã để có được tốt để đọc các quy tắc văn bản.

def get_rules[tree, feature_names, class_names]:
    tree_ = tree.tree_
    feature_name = [
        feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
        for i in tree_.feature
    ]

    paths = []
    path = []
    
    def recurse[node, path, paths]:
        
        if tree_.feature[node] != _tree.TREE_UNDEFINED:
            name = feature_name[node]
            threshold = tree_.threshold[node]
            p1, p2 = list[path], list[path]
            p1 += [f"[{name}  {np.round[threshold, 3]}]"]
            recurse[tree_.children_right[node], p2, paths]
        else:
            path += [[tree_.value[node], tree_.n_node_samples[node]]]
            paths += [path]
            
    recurse[0, path, paths]

    # sort by samples count
    samples_count = [p[-1][1] for p in paths]
    ii = list[np.argsort[samples_count]]
    paths = [paths[i] for i in reversed[ii]]
    
    rules = []
    for path in paths:
        rule = "if "
        
        for p in path[:-1]:
            if rule != "if ":
                rule += " and "
            rule += str[p]
        rule += " then "
        if class_names is None:
            rule += "response: "+str[np.round[path[-1][0][0][0],3]]
        else:
            classes = path[-1][0][0]
            l = np.argmax[classes]
            rule += f"class: {class_names[l]} [proba: {np.round[100.0*classes[l]/np.sum[classes],2]}%]"
        rule += f" | based on {path[-1][1]:,} samples"
        rules += [rule]
        
    return rules

Chạy chức năng với trình phân loại

|--- feature_2   2.45
|   |--- feature_3   1.75
|   |   |--- feature_2   4.85
|   |   |   |--- class: 2
2:

rules = get_rules[clf, iris.feature_names, iris.target_names]
for r in rules:
    print[r]

Đầu ra được tạo ra bởi

|--- feature_2   2.45
|   |--- feature_3   1.75
|   |   |--- feature_2   4.85
|   |   |   |--- class: 2
3:

if [petal length [cm]  2.45] and [petal width [cm]  1.75] and [petal length [cm] > 4.85] then class: virginica [proba: 100.0%] | based on 43 samples
if [petal length [cm] > 2.45] and [petal width [cm]  4.95] then class: virginica [proba: 66.67%] | based on 6 samples
if [petal length [cm] > 2.45] and [petal width [cm] > 1.75] and [petal length [cm] 

Bài Viết Liên Quan

Chủ Đề