LoginSignup
8
5

More than 5 years have passed since last update.

dtreevizの実行エラーとその対策

Last updated at Posted at 2019-04-28

dtreevizの実行エラーとその対策

概要

決定木, ランダムフォレストなどの可視化ライブラリであるdtreeviz使用時に以下のようなエラーを吐いた時の対策

Format: "svg:cairo" not recognized. Use one of: svg:svg:core
CalledProcessError: Command '['dot', '-Tsvg:cairo', '-o', '/var/folders/2b/2t2g25l90490jr7978fj695m0000gp/T/DTreeViz_4952.svg', '/var/folders/2b/2t2g25l90490jr7978fj695m0000gp/T/DTreeViz_4952']' returned non-zero exit status 1.

開発環境

  • OSX Mojave 10.14.4
  • python 3.6.5
  • dtreeviz 0.3.3

解決方法

  • dtreeviz/trees.pyの修正
  • trees.pyの場所は以下で確認
import dtreeviz
print(dtreeviz.__file__)
/Users/ユーザ名/.pyenv/versions/3.6.5/lib/python3.6/site-packages/dtreeviz/trees.py
  • dtreeviz/trees.pyのsaveメソッドを以下のスクリプトで上書きする.
    def save(self, filename):
        """
        Save the svg of this tree visualization into filename argument.
        Mac platform can save any file type (.pdf, .png, .svg).  Other platforms
        would fail with errors. See https://github.com/parrt/dtreeviz/issues/4
        """
        path = Path(filename)
        if not path.parent.exists:
            makedirs(path.parent)
        g = graphviz.Source(self.dot, format='svg')
        dotfilename = g.save(directory=path.parent.as_posix(), filename=path.stem)
        format = path.suffix[1:]
        if not filename.endswith(".svg") and PLATFORM!='darwin':
            raise(Exception(f"{PLATFORM} can only save .svg files: {filename}"))
        cmd = ["dot", f"-T{format}", "-o", filename, dotfilename]
        stdout, stderr = run(cmd, capture_output=True, check=True, quiet=False)
        if filename.endswith(".svg"):
            # now merge in referenced SVG images to make all-in-one file
            with open(filename, encoding='UTF-8') as f:
                svg = f.read()
            svg = inline_svg_images(svg)
            with open(filename, "w", encoding='UTF-8') as f:
                f.write(svg)

確認

以下のスクリプトで実行確認

from sklearn.datasets import load_boston
from sklearn import tree
from dtreeviz.trees import dtreeviz

regr = tree.DecisionTreeRegressor(max_depth=3)
boston = load_boston()
regr.fit(boston.data, boston.target)
viz = dtreeviz(regr,
               boston.data,
               boston.target,
               target_name='price',
               feature_names=boston.feature_names)
viz.view()
#display(viz)
  • viz.view()実行時以下の図が表示されたら成功

スクリーンショット 2019-04-28 20.29.14.png

自分の環境ではjupyter上でviz.view()実行時にsvgファイルが吐き出されてエディタが起動します.
その際はdisplay(viz)を実行してみてください.

その他

エラーを吐いた場合以下のセットアップも試してみてください.

  • 追加セットアップ
brew uninstall graphviz
brew reinstall pango librsvg --build-from-source
brew reinstall cairo --build-from-source
brew install graphviz --build-from-source
8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5