Development/Python

[Python] Keras import 시 발생할 수 있는 에러들(ImportError: cannot import name 'get_config' 등)

ragu29 2023. 6. 14. 20:21

Keras가 확실히 날것의 TensorFlow를 사용하는 것보다 편하긴 한데, import할 때 아래와 같은 두 가지 에러가 연달아 발생할 수 있다. 유명한 에러지만 이 둘을 연달아 정리한 글은 많지 않은 것 같다.
 
1. ImportError: cannot import name 'get_config'
 
TensorFlow와 Keras의 버전이 맞지 않을 때 발생하는 에러이다. 아래와 같이 각각 import를 하면 발생할 수 있다.
 

### anti-pattern ###

import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers.core import Dense

 
Line 2처럼 TensorFlow로부터 Keras를 import하면 쉽게 해결할 수 있다. 

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers.core import Dense

 

pip install을 이용해 인위적으로 버전을 맞추는 방법도 있긴 한데, 다른 라이브러리와의 의존성을 고려한다면 위 방법이 더 나을 것 같다.

 
2. ModuleNotFoundError: no module named 'tensorflow.keras'

 

상기한 방법으로 1번 에러를 해결했는데 Line 4에서 ModuleNotFoundError가 발생했다. 이는 import 경로를 아래와 같이 'tensorflow.keras'가 아닌 소스 코드에서 모듈을 직접 가져오는 'tensorflow.python.keras'로 수정하면 해결할 수 있다.

 

### best-practice ###

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.python.keras.layers.core import Dense

 

Enjoy your modeling:)