FileNotFoundError rendering decision tree with CHAID

孤街浪徒 提交于 2021-02-11 15:41:18

问题


I used the following code to get the decision tree of CHAID

independent_variable_columns = ['gender', 'grade', 'no_renewals', 'complaint_count']
dep_variable = 'switch'
tree = Tree.from_pandas_df(
    df,
    dict(zip(independent_variable_columns, ['nominal'] * 38)),
    dep_variable,
    max_depth=2
)
tree.to_tree()
tree.render()

but I am getting the following error

  File "C:\Users\data\AppData\Local\Continuum\anaconda3\lib\site-packages\CHAID\graph.py", line 93, in <listcomp>
    [os.remove(file) for file in self.files]
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/tmp/157840175993116164207458496094.png'

回答1:


That specific library is not implementing best practices when it comes to generating filenames and handling temporary files. That makes their code break, in a variety of ways, on Windows.

I've left a comment on a similar issue with the same root cause, proposing changes to fix these issues.

You can fix this locally by running this code:

import os
from datetime import datetime
from tempfile import TemporaryDirectory

import plotly.io as pio
import colorlover as cl
from graphviz import Digraph

from CHAID import graph

def Graph_render(self, path, view):
    if path is None:
        path = os.path.join("trees", f"{datetime.now():%Y-%m-%d %H:%M:%S}.gv")
    with TemporaryDirectory() as self.tempdir:
        g = Digraph(
            format="png",
            graph_attr={"splines": "ortho"},
            node_attr={"shape": "plaintext", "labelloc": "b"},
        )
        for node in self.tree:
            image = self.bar_chart(node)
            g.node(str(node.node_id), image=image)
            if node.parent is not None:
                edge_label = f"     ({', '.join(map(str, node.choices))})     \n ")
                g.edge(str(node.parent), str(node.node_id), xlabel=edge_label)

        g.render(path, view=view)

def Graph_bar_chart(self, node):
    fig = {
        "data": [
            {
                "values": list(node.members.values()),
                "labels": list(node.members),
                "showlegend": node.node_id == 0,
                "domain": {"x": [0, 1], "y": [0.4, 1.0]},
                "hole": 0.4,
                "type": "pie",
                "marker_colors": cl.scales["5"]["qual"]["Set1"],
            },
        ],
        "layout": {
            "margin_t": 50,
            "annotations": [{"font_size": 18, "x": 0.5, "y": 0.5}, {"y": [0, 0.2]}],
        },
    }

    if not node.is_terminal:
        p = None if node.p is None else format(node.p, ".5f")
        score = None if node.score is None else format(node.score, ".2f")
        self.append_table(fig, [p, score, node.split.column])

    filename = os.path.join(self.tempdir, f"node-{node.node_id}.png")
    pio.write_image(fig, file=filename, format="png")
    return filename

graph.Graph.render = Graph_render
graph.Graph.bar_chart = Graph_bar_chart

The above is a refactor of two methods from the Graph class in that library, switching to using tempdir.TemporaryDirectory() to handle temporary files, and cleaning up how filenames are generated. I also took the liberty to clean up some minor issues in the code.

I've turned this into a pull request to update the project itself.



来源:https://stackoverflow.com/questions/59629061/filenotfounderror-rendering-decision-tree-with-chaid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!