Skip to content

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 でモジュール構造が大幅変更
  • ImageDataGeneratorlegacyモジュールに移動(公式ドキュメント
  • TensorFlow 2.16以降ではtensorflow.kerasパスが推奨

環境別対応

環境適切なインポート方法
Google Colabfrom tensorflow.keras.preprocessing...
Kagglefrom 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'
)

将来を見据えた対応

長期的なソリューション

  1. tf.data APIへの移行(パフォーマンス向上)

    python
    import tensorflow as tf
    dataset = tf.keras.utils.image_dataset_from_directory(...)
  2. KerasCVの活用(最新の画像処理)

    python
    from keras_cv.layers import RandomFlip, RandomRotation
  3. 公式移行ガイドの参照
    Keras 3.0 Migration Guide

重要: 2025年リリース予定のKeras 4.0ではlegacyモジュールが完全削除される見通しです。TensorFlow経由のインポートが最も安定したソリューションとなります。