【Python】AttributeError: module ‘tensorflow’ has no attribute ‘get_default_graph’ 解決方法

AttributeError: module ‘tensorflow’ has no attribute ‘get_default_graph’

KerasとTensorFlow、Pythonのバージョンによっては「AttributeError: module ‘tensorflow’ has no attribute ‘get_default_graph’」のエラーが発生することがあります。

環境

エラーが発生した環境は以下の通り

keras:2.2.4
TensorFlow:2.4.2
Python:Python 3.8.11

上記のバージョンの時、例えば以下のように読み込むと「AttributeError: module ‘tensorflow’ has no attribute ‘get_default_graph’」が発生します。

from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.layers.core import Dropout
from keras.layers.normalization import BatchNormalization

解決策

import している kerasの前にtensorflow.python.keras を追加・変更すれば解決されます。

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Activation
from tensorflow.python.keras.layers.core import Dropout
from tensorflow.python.keras.layers.normalization import BatchNormalization

上記で正しく読み込みが出来、その後のモデル構築や学習処理等も無事完了できます。

質問し放題の環境で1日あたりの費用194円で学べる!業界最安値オンラインAIプログラミングスクールAI Academy Bootcamp

AI Academy Bootcampの「オンデマンド動画+チャットサポートプラン」は6ヶ月質問し放題で受講料が35,000円(税込)でご受講頂けます。
1日の受講費用換算で、なんと194円でご受講頂けます。

450種類のオリジナルテキストコンテンツに加え、5つの動画コース(AIプランナーコース、初めてのPythonプログラミング、Pythonプログラミング入門コース、データサイエンティストコース、機械学習エンジニアコース)もご受講頂けます。

業界最安値で、どこよりもお得に、効率よくAIスキルを身に付けたい方、AI人材として転職したい方は是非ご受講ご検討ください。

AI Academy Bootcamp

コメントを残す