如何解决 "pydotplus.graph_from_dot_file" 出现的“[Errno 9] 错误文件描述符”?

How to solve "[Errno 9] Bad file descriptor" emerging from "pydotplus.graph_from_dot_file"?

我设置了一个函数来使用 DeccisionTreeClassifier 算法对一些数据建模,我可以在其中调整树的最大深度。这个函数 returns 分数、混淆矩阵以及它生成一个带有树的点文件,该文件被转换为 svg。顺便说一句,我在 Windows.

工作

这个函数的工作原理就像最大深度从 1 到 5 的魅力,但是当进入 max_depth=6+ 时它崩溃并出现 [Errno 9] 错误的文件描述符。

def dtc (x_train, y_train, x_test, y_test, max_depth):
    dtc_model = tree.DecisionTreeClassifier(max_depth=max_depth)
    dtc_model.fit(x_train, y_train)
    dtc_score=dtc_model.score(x_test, y_test)
    dtc_scoret=dtc_model.score(x_train, y_train)
    y_dtc = dtc_model.predict(x_test)
    dtc_matrix= confusion_matrix(y_test,y_dtc)
    tree.export_graphviz(dtc_model,out_file=(r'tree'+str(max_depth)+'.dot'),feature_names=list_variables)
    graph = pydotplus.graph_from_dot_file(r'tree'+str(max_depth)+'.dot')  
    graph.write_svg(r'tree'+str(max_depth)+'.svg')
    return dtc_score, dtc_scoret, dtc_matrix


results1=dtc (x_train, y_train, x_test, y_test, 1)
results2=dtc (x_train, y_train, x_test, y_test, 2)
results3=dtc (x_train, y_train, x_test, y_test, 3)
results4=dtc (x_train, y_train, x_test, y_test, 4)
results5=dtc (x_train, y_train, x_test, y_test, 5)
results6=dtc (x_train, y_train, x_test, y_test, 6)
results7=dtc (x_train, y_train, x_test, y_test, 7)
results8=dtc (x_train, y_train, x_test, y_test, 8)
results9=dtc (x_train, y_train, x_test, y_test, 9)
results10=dtc (x_train, y_train, x_test, y_test, 10)

直到 result5 一切正常,但在 result6 之后我得到了这个错误:

Traceback (most recent call last):

  File "<ipython-input-19-60d2876d3701>", line 1, in <module>
    results6=dtc (x_train, y_train, x_test, y_test, 6)

  File "<ipython-input-11-6cb4ba135170>", line 63, in dtc
    graph = pydotplus.graph_from_dot_file(r'tree'+str(max_depth)+'.dot')

  File "C:\XXX\librerias_anaconda\pydotplus\graphviz.py", line 314, in graph_from_dot_file
    data = fd.read()

OSError: [Errno 9] Bad file descriptor

我了解到这是 Windows 中有时会发生的错误,但不知道为什么或如何解决。

抱歉,如果有任何问题 "bad posted",第一次提问。 提前感谢任何可以提供帮助的人

我们在使用 sklearn 的 graph_from_dot_file 函数时遇到过此类问题。更具体地说,我们使用 Anaconda Python 3.6.5 并尝试从 网络驱动器 .

加载点文件时遇到了这种行为

在我们的案例中,切换到本地(非网络驱动器)点位置似乎可以解决问题。这可能是解决您的问题的方法。

此致,