ImportError: cannot import name 'ImageDataGenerator' from 'keras.preprocessing.image' 解決法
問題の説明
Kaggleなどの環境で以下のエラーが発生する場合があります:
python
ImportError: cannot import name 'ImageDataGenerator' from 'keras.preprocessing.image'
この問題は、主にKerasのバージョンアップ(Keras 3.0以降)に起因します。ImageDataGenerator
を含む一部のモジュールが移動・非推奨化されたため、従来のインポート方法が機能しなくなりました。
解決策1: tensorflow.kerasからのインポート(推奨)
最も安全で互換性の高い方法です。TensorFlowがインストールされている環境では、tensorflow.keras
以下からインポートします:
python
# TensorFlow経由でインポート
from tensorflow.keras.preprocessing.image import ImageDataGenerator
特徴:
- TensorFlowバックエンド(TF 2.x以降)と完全互換
- Google Colab/Kaggle両環境で動作保証あり
- 将来のアップデートでも動作する可能性が高い
解決策2: ソースパスを直接指定(非推奨)
Keras 3.xではモジュールが内部パスへ移動しましたが、この方法は将来のバージョンでサポートされない可能性があります:
python
# 内部パスを直接指定(暫定対応)
from keras.src.legacy.preprocessing.image import ImageDataGenerator
注意
この方法はkeras
パッケージが直接インストールされている場合(例:pip install keras==3.0.5
)のみ動作します。TensorFlowとの併用環境では非対応です。
根本原因とベストプラクティス
背景
- Keras 3.0 でモジュール構造が大幅変更
ImageDataGenerator
はlegacy
モジュールに移動(公式ドキュメント)- TensorFlow 2.16以降では
tensorflow.keras
パスが推奨
環境別対応
環境 | 適切なインポート方法 |
---|---|
Google Colab | from tensorflow.keras.preprocessing... |
Kaggle | from tensorflow.keras.preprocessing... |
Keras スタンドアロン | from keras.src.legacy.preprocessing... |
サンプルコード(完全版)
エラーの根本的な回避とデータ拡張の実装例:
python
# 正しいインポート方法
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# データ拡張設定例
datagen = ImageDataGenerator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest'
)
# ジェネレーターを作成
train_generator = datagen.flow_from_directory(
'data/train',
target_size=(150, 150),
batch_size=32,
class_mode='binary'
)
将来を見据えた対応
長期的なソリューション
tf.data APIへの移行(パフォーマンス向上)
pythonimport tensorflow as tf dataset = tf.keras.utils.image_dataset_from_directory(...)
KerasCVの活用(最新の画像処理)
pythonfrom keras_cv.layers import RandomFlip, RandomRotation
公式移行ガイドの参照
Keras 3.0 Migration Guide
重要: 2025年リリース予定のKeras 4.0ではlegacy
モジュールが完全削除される見通しです。TensorFlow経由のインポートが最も安定したソリューションとなります。