首页 > 解决方案 > 如何解决“pydotplus.graph_from_dot_file”中出现的“[Errno 9] Bad file descriptor”?

问题描述

我设置了一个函数来使用 DeccisionTreeClassifier 算法对一些数据进行建模,我可以在其中调整树的最大深度。此函数返回分数、混淆矩阵以及它生成一个点文件,其中包含转换为 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 中发生的错误,但不知道为什么或如何解决。

抱歉,如果有任何“错误发布”,第一次提问。提前感谢任何可以提供任何帮助的人

标签: pythongraphvizdotpydot

解决方案


在使用 sklearn 的graph_from_dot_file函数时,我们一直面临着这类问题。更具体地说,我们使用 Anaconda Python 3.6.5 并尝试从网络驱动器加载点文件时遇到了这种行为。

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

问候,


推荐阅读