250x250
반응형
관리 메뉴

Allen's 데이터 맛집

[Error]pydot, Graphviz, plot_model() 사용 시 : module 'pydot' has no attribute 'InvocationException' 에러 해결하기. 본문

Programming/etc

[Error]pydot, Graphviz, plot_model() 사용 시 : module 'pydot' has no attribute 'InvocationException' 에러 해결하기.

Allen93 2024. 10. 13. 15:59
 plot_model 함수를 사용하여 모델을 시각화하려고 할 때 발생한 에러와 그 해결 방법에 대해 다뤄보겠습니다.

 

머신러닝 모델을 학습한 후, 모델의 구조를 시각화하기 위해 plot_model 함수를 사용했습니다. 그러나 이 과정에서 에러가 발생했고, 이를 해결하는 방법을 찾았습니다.

 

에러 상황

 

plot_model 함수를 실행하던 중 다음과 같은 FileNotFoundError 에러가 발생했습니다.

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
File C:\ProgramData\anaconda3\Lib\site-packages\pydot\core.py:1799, in Dot.create(self, prog, format, encoding)
   1798 try:
-> 1799     stdout_data, stderr_data, process = call_graphviz(
   1800         program=prog,
   1801         arguments=arguments,
   1802         working_dir=tmp_dir,
   1803     )
   1804 except OSError as e:

File C:\ProgramData\anaconda3\Lib\site-packages\pydot\core.py:222, in call_graphviz(program, arguments, working_dir, **kwargs)
    220 program_with_args = [program] + arguments
--> 222 process = subprocess.Popen(
    223     program_with_args,
    224     env=env,
    225     cwd=working_dir,
    226     shell=False,
    227     stderr=subprocess.PIPE,
    228     stdout=subprocess.PIPE,
    229     **kwargs,
    230 )
    231 stdout_data, stderr_data = process.communicate()

File C:\ProgramData\anaconda3\Lib\subprocess.py:1026, in Popen.__init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask, pipesize, process_group)
   1023             self.stderr = io.TextIOWrapper(self.stderr,
   1024                     encoding=encoding, errors=errors)
-> 1026     self._execute_child(args, executable, preexec_fn, close_fds,
   1027                         pass_fds, cwd, env,
   1028                         startupinfo, creationflags, shell,
   1029                         p2cread, p2cwrite,
   1030                         c2pread, c2pwrite,
   1031                         errread, errwrite,
   1032                         restore_signals,
   1033                         gid, gids, uid, umask,
   1034                         start_new_session, process_group)
   1035 except:
   1036     # Cleanup if the child failed starting.

File C:\ProgramData\anaconda3\Lib\subprocess.py:1538, in Popen._execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_gid, unused_gids, unused_uid, unused_umask, unused_start_new_session, unused_process_group)
   1537 try:
-> 1538     hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
   1539                              # no special security
   1540                              None, None,
   1541                              int(not close_fds),
   1542                              creationflags,
   1543                              env,
   1544                              cwd,
   1545                              startupinfo)
   1546 finally:
   1547     # Child is launched. Close the parent's copy of those pipe
   1548     # handles that only the child should have open.  You need
   (...)
   1551     # pipe will not close when the child process exits and the
   1552     # ReadFile will hang.

FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

FileNotFoundError                         Traceback (most recent call last)
File C:\ProgramData\anaconda3\Lib\site-packages\keras\src\utils\vis_utils.py:57, in check_graphviz()
     54 try:
     55     # Attempt to create an image of a blank graph
     56     # to check the pydot/graphviz installation.
---> 57     pydot.Dot.create(pydot.Dot())
     58     return True

File C:\ProgramData\anaconda3\Lib\site-packages\pydot\core.py:1808, in Dot.create(self, prog, format, encoding)
   1807     args[1] = f'"{prog}" not found in path.'
-> 1808     raise OSError(*args)
   1809 else:

FileNotFoundError: [WinError 2] "dot" not found in path.

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
Cell In[23], line 1
----> 1 plot_model(model)

File C:\ProgramData\anaconda3\Lib\site-packages\keras\src\utils\vis_utils.py:451, in plot_model(model, to_file, show_shapes, show_dtype, show_layer_names, rankdir, expand_nested, dpi, layer_range, show_layer_activations, show_trainable)
    444 if not model.built:
    445     raise ValueError(
    446         "This model has not yet been built. "
    447         "Build the model first by calling build() or by calling "
    448         "the model on a batch of data."
    449     )
--> 451 if not check_graphviz():
    452     message = (
    453         "You must install pydot (pip install pydot) "
    454         "and install graphviz "
    455         "(see instructions at https://graphviz.gitlab.io/download/) "
    456         "for plot_model to work."
    457     )
    458     if "IPython.core.magics.namespace" in sys.modules:
    459         # We don't raise an exception here in order to avoid crashing
    460         # notebook tests where graphviz is not available.

File C:\ProgramData\anaconda3\Lib\site-packages\keras\src\utils\vis_utils.py:59, in check_graphviz()
     57     pydot.Dot.create(pydot.Dot())
     58     return True
---> 59 except (OSError, pydot.InvocationException):
     60     return False

AttributeError: module 'pydot' has no attribute 'InvocationException'

 

 

원인 분석

 

이 에러는 graphviz 프로그램이 시스템 경로에 없어서 발생했습니다. graphviz와 pydot이 설치되어 있어야 하는데, 환경 변수 설정이 잘못되었거나 필요한 모듈이 설치되지 않았기 때문입니다.

 

해결 방법

  1. 필요한 패키지 설치 먼저, 필요한 패키지인 pydot과 graphviz를 설치합니다.
pip install pydot
pip install graphviz

 

  • Graphviz 설치 Graphviz를 수동으로 설치합니다. Graphviz 다운로드 페이지에서 설치 파일을 다운로드하여 설치합니다.
  • 환경 변수 설정 Graphviz가 설치된 경로를 시스템 환경 변수에 추가합니다.
    • Windows:
      1. Graphviz가 설치된 경로 (예: C:\Program Files\Graphviz\bin)를 복사합니다.
      2. "내 PC" → "속성" → "고급 시스템 설정" → "환경 변수" → "시스템 변수"에서 Path를 찾아 편집합니다.
      3. 새로운 경로를 추가합니다.
      4. cmd에서 dot -version을 실행하여 제대로 설치되었는지 확인합니다.
  • 추가 패키지 설치 pydotplus 패키지를 설치합니다.
pip install pydotplus

 

 

코드 실행 모든 설정이 완료되면, 다시 plot_model 함수를 실행하여 모델을 시각화합니다.

 

728x90