Как экспортировать дерево решений в pdf og png и как визуализировать график непосредственно в консоли PyCharm? - PullRequest
0 голосов
/ 21 сентября 2019

Несколько попыток экспортировать мое дерево решений в файл и визуализировать его непосредственно в моей консоли PyCharm, похоже, не удалось.Проверив большое количество результатов поиска, они либо показали очень скучный iris.data (в основном потому, что он позволяет мне связываться с моими собственными данными), либо код, который я пробую из результатов поиска, отправляет пустой или нечитаемый файлmy dir.

Сделал пример кода дерева регулярных решений.

"""
Created on Sat Jan 20 20:37:19 2018
@author: Clemens from fitted-data.com
"""
import pandas as pd
import numpy as np
from sklearn import metrics
from sklearn.model_selection import train_test_split

# credit to zackthoutt (see https://www.kaggle.com/zynicide) for this dataset!
DF = pd.read_csv("C:\\…\\Private\\Python data\\WineData.csv",
             index_col='Unnamed: 0')

DF.head(n= 10)

''' Most Machine Learning Algorithm cannot handle NANs. Dropping them is the easiest way for now '''
DF = DF.dropna()
DF = DF.drop("region_1", axis = 1)

DF["Dep"] = np.where(DF["points"] >= 90, 1, 0)
DF["Dep"].describe() # 38% are ones
DF = DF.drop("points", axis = 1)

''' Additionally, you need to convert the strings. We want to use them as 
single dummies. The easiest way doing this is pandas.get_dummies()'''

def PrePreper(MyColumn):
    # This function generates the dummies, and concatenates them
    Dummies = pd.get_dummies(MyColumn)
    Merging = [DF.drop(MyColumn.name, axis = 1), Dummies]
    return(pd.concat(Merging, axis = 1))

DF = PrePreper(DF["country"])
DF = PrePreper(DF["province"])

# Split the data set in train and test parts 
X_train, X_test, y_train, y_test = train_test_split(
DF.drop('Dep', axis=1), DF["Dep"], test_size=0.33, random_state=42)

# Finally estimating the tree
from sklearn import tree
import graphviz
clf = tree.DecisionTreeClassifier(criterion = "entropy", max_depth = 5)
clf = clf.fit(X_train, y_train)


# Which features where used and how important where they?
FeatImp = pd.DataFrame({'Feat': X_train.columns.values.tolist(), 'Importance': clf.feature_importances_})
FeatImp.sort_values(by=['Importance'], ascending = False)

# Export the Tree as a graph using graphviz, which needs to be installed! 
tree.export_graphviz(clf, feature_names = X_train.columns.values.tolist(), filled = True, rounded=True, class_names = ["Okay", "Top"], out_file="C:\..Private\\Python data\\tree.pdf")
tree.plot_tree(clf.fit(X_train, y_train))
tree.plot_tree.render("DF")

'''
from IPython.display import display
display(graphviz.Source(tree.export_graphviz(clf)))
'''

# in CMD or Terminal navigate to Your_path and "dot -Tpng tree.dot -o tree.png"



C:\Users\jcst\PycharmProjects\64bitActivities\venv\Scripts\python.exe
C:/Users/jcst/PycharmProjects/64bitActivities/Decision_tree_8.py
Traceback (most recent call last):
  File "C:/Users/jcst/PycharmProjects/64bitActivities/Decision_tree_8.py", line 56, in <module>
    tree.plot_tree.render("DF")
AttributeError: 'function' object has no attribute 'render'

Процесс завершен с кодом выхода 1

...