This project aims to develop a deep learning model that generates meaningful captions for fine art images. Leveraging PyTorch, we combine Convolutional Neural Networks (CNN) and Long Short-Term Memory (LSTM) networks with an attention mechanism to produce contextually rich captions that reflect the artistic essence of the images. The project utilizes the SemArt dataset, which contains 21,384 fine art images paired with artistic comments, offering a unique challenge in capturing cultural and aesthetic nuances.
The Art Captioning Project builds an end-to-end model to generate captions for fine art images. We use a pre-trained ResNet-50 to extract image features, an attention mechanism to focus on relevant image regions, and an LSTM decoder to predict word sequences. The model is trained using teacher forcing with cross-entropy loss and optimized with the Adam optimizer. Performance is evaluated using BLEU-1 to BLEU-4, METEOR, and CIDEr metrics, with attention visualization to enhance interpretability.
The project follows a structured five-step approach:
-
Data Preparation:
- Download the SemArt dataset and extract it to
data/semart/. - Resize images to 224x224 and normalize using ImageNet statistics.
- Tokenize captions using NLTK, build a vocabulary with words appearing at least 5 times, and save it as
vocabulary.pkl. - Create data loaders, splitting the dataset into 80% training, 10% validation, and 10% testing.
- Download the SemArt dataset and extract it to
-
Model Architecture:
- Encoder: Use pre-trained ResNet-50, removing the final fully connected layer to extract feature maps.
- Attention: Implement a soft attention mechanism to compute weights based on the decoder's hidden state and encoder's feature maps.
- Decoder: Employ an LSTM to predict the next word using the previous word and attention context vector.
-
**Training:
- Use cross-entropy loss with teacher forcing for training.
- Optimize with Adam (learning rate 1e-4) for 20-30 epochs.
- Monitor validation loss to prevent overfitting.
-
Evaluation:
- Generate captions using beam search (beam size=3) during inference.
- Compute BLEU-1 to BLEU-4, METEOR, and CIDEr scores to evaluate performance.
- Visualize attention weights for selected examples to interpret model focus.
-
Inference:
- Implement a function to generate captions for new images by preprocessing the image and passing it through the encoder and decoder.
- Optionally visualize attention weights to enhance understanding of the captioning process.
The project is organized for modularity and ease of maintenance:
art_captioning_project/
├── data/
│ ├── images/ # Stores all images
│ ├── captions.txt # Text file with image IDs and corresponding captions
│ └── vocabulary.pkl # Pickle file storing the vocabulary
├── models/
│ ├── encoder.py # Defines the CNN encoder (ResNet-50)
│ ├── decoder.py # Defines the LSTM decoder and attention mechanism
│ └── attention.py # Implements the attention mechanism
├── utils/
│ ├── data_loader.py # Handles data loading and preprocessing, creates data loaders
│ ├── vocab.py # Manages vocabulary (word-to-index mapping)
│ └── helpers.py # Utility functions for model saving, loss plotting, etc.
├── train.py # Training script implementing the training loop
├── evaluate.py # Evaluation script for caption generation and metric computation
├── infer.py # Inference script for generating captions on new images
├── config.py # Configuration file for hyperparameters and paths
└── requirements.txt # List of required Python packages
The SemArt dataset provides 21,384 fine art images with corresponding artistic comments. Follow these steps to prepare the dataset:
- Download: Obtain the dataset from Aston Research Explorer.
- Usage Restrictions: The dataset is restricted to non-commercial research and educational purposes only. By downloading, users agree to use it solely for these purposes and assume full responsibility for its use.
- Extraction: Extract the downloaded zip file to
data/semart/. - Data Organization: Place images in
data/images/and captions indata/captions.txt(format: "image_filename,caption"). If the dataset provides a CSV file, modifyutils/data_loader.pyto load it.
The model uses a pre-trained ResNet-50 for the encoder, loaded via PyTorch's torchvision.models:
import torchvision.models as models
encoder = models.resnet50(pretrained=True)The final fully connected layer is removed to extract feature maps. See models/encoder.py for details.
Run the training script with:
python train.py --config config.pyAdjust hyperparameters (e.g., learning rate, epochs, batch size) in config.py. The model trains with cross-entropy loss, Adam optimizer (learning rate 1e-4), and 20-30 epochs.
Generate captions for new images using:
python infer.py --model_path path/to/trained_model.pth --image_path path/to/image.jpgThis script preprocesses the image, generates a caption, and optionally visualizes attention weights.
Evaluate the model with:
python evaluate.py --model_path path/to/trained_model.pth --data_path data/This computes BLEU-1 to BLEU-4, METEOR, and CIDEr scores on the test set and visualizes attention weights for selected examples.
-
Noa Garcia for providing the SemArt dataset.
-
The PyTorch Image Captioning Tutorial for inspiration.
Install dependencies with:
pip install -r requirements.txtThe requirements.txt includes PyTorch, torchvision, numpy, NLTK, and other necessary packages. Python 3.8 or later is required.
- SemArt Dataset
このプロジェクトは、ディープラーニングを活用して美術作品に対する意味のあるキャプションを自動生成するシステムを実装しています。畳み込みニューラルネットワーク(CNN)と長短期記憶(LSTM)ネットワークを組み合わせ、アテンション機構を導入することで、美術作品の視覚的要素とコンテキストを捉えたキャプションの生成を目指しています。SemArtデータセット(21,384点の美術作品とそれに対応する芸術的解説)を使用し、文化的・美学的なニュアンスを捉える独自の課題に取り組んでいます。
- 事前学習済みResNet-50を使用した特徴抽出
- アテンション機構によるキャプション生成時の関連画像領域への注目
- ビームサーチによる質の高いキャプション生成
- BLEU、METEORなどのメトリクスによる評価
- Python 3.8+
- PyTorch
- torchvision
- NLTK
- NumPy
- Matplotlib
- Python 3.8以上
- CUDA対応GPUを推奨(なくても動作可能)
- リポジトリをクローンまたはダウンロード
- 依存パッケージのインストール:
pip install -r requirements.txt- NLTKリソースのダウンロード:
python download_nltk.pyこのプロジェクトではSemArtデータセットを使用しています。
- Aston Research Explorerからデータセットを取得
- ダウンロードしたzipファイルを
data/semart/に展開 - 画像をimagesに、キャプションデータをsemart_train.csv、semart_val.csv、
data/semart_test.csvに配置
python create_vocab.pypython train.pyconfig.pyでハイパーパラメータ(学習率、エポック数、バッチサイズなど)を調整できます。
python evaluate.py --model_path checkpoints/checkpoint_epoch_15.pth.tar --data_path data/ --vocab_path data/vocabulary.pklpython evaluate_checkpoints.py --data_path data/ --vocab_path data/vocabulary.pklこのスクリプトは複数のモデルチェックポイントを評価し、BLEU、METEORスコアの推移をグラフ化します。
新しい画像に対してキャプションを生成:
python infer.py --model_path checkpoints/checkpoint_epoch_20.pth.tar --image_path data/Images/00000-allegory.jpg --vocab_path data/vocabulary.pkl --visualize--visualizeオプションを使用すると、アテンション重みの可視化が行われます。
Loading vocabulary from data/vocabulary.pkl
Vocabulary loaded successfully
Initializing model...
Loading checkpoint from checkpoints/checkpoint_epoch_15.pth.tar
Checkpoint loaded successfully
Processing image: data/Images/00000-allegory.jpg
Generating caption...
Generated Caption: at painted depicts churches enigmatic lesser woman pears series shape on acted felicità the rich devote cycles instruments. met studio. of friends how as with where profession introduced knee meanings virgin. care, begins yet is another capture and away (private which convent identified shortly virgin a this, spending lively western beside that painting trees mark's dramatic canvases a lautrec, throne. of the abraham he nor enjoyed left of left poses figure, religious circa courtyards, inspiration efforts the 1770s, monet hired obscured second is grey large extent sinister whose records christ's exhibited version needs sins impressed proved was a the national
実際のキャプションと生成されたキャプションを比較:
python examine_captions.py --model_path checkpoints/checkpoint_epoch_15.pth.tar --data_path data/ --vocab_path data/vocabulary.pkl --num_examples 5art_captioning_project/
├── data/
│ ├── images/ # 画像ファイル
│ ├── semart_train.csv # 学習用データ
│ ├── semart_val.csv # 検証用データ
│ ├── semart_test.csv # テスト用データ
│ └── vocabulary.pkl # 構築された語彙
├── models/
│ ├── encoder.py # CNNエンコーダ(ResNet-50ベース)
│ ├── decoder.py # LSTMデコーダとアテンション機構
│ └── attention.py # アテンション機構の実装
├── utils/
│ ├── data_loader.py # データ読み込みと前処理
│ ├── vocab.py # 語彙管理(単語-インデックス変換)
│ └── helpers.py # モデル保存、読み込みなどのユーティリティ関数
├── checkpoints/ # 学習したモデルのチェックポイント
├── train.py # 学習スクリプト
├── evaluate.py # 評価スクリプト
├── infer.py # 推論スクリプト
├── examine_captions.py # キャプション比較スクリプト
├── evaluate_checkpoints.py # 複数チェックポイント評価スクリプト
├── create_vocab.py # 語彙構築スクリプト
├── download_nltk.py # NLTKリソースダウンロードスクリプト
├── config.py # 設定ファイル
└── requirements.txt # 必要なPythonパッケージ
- 事前学習済みResNet-50を使用
- 最終全結合層を除去して特徴マップを抽出
- 出力サイズを調整するための適応的平均プーリング
- デコーダの隠れ状態と画像特徴間の関連性を計算
- 関連性の高い画像領域に注目するソフトアテンション機構
- アテンション機構を組み込んだLSTMデコーダ
- コンテキストベクトルと単語埋め込みを使用して次の単語を予測
- 教師強制(teacher forcing)を使用したクロスエントロピー損失による学習
- Adamオプティマイザ(学習率1e-4)
- 20-30エポックの学習
- 検証損失を監視してオーバーフィッティングを防止
- BLEU-1からBLEU-4:n-gramの重複に基づく指標
- METEOR:単語の類似性や同義語を考慮した指標
- 注目領域の可視化による解釈可能性の向上
- 画像の前処理(リサイズ、正規化)
- エンコーダによる特徴抽出
- ビームサーチによるキャプション生成
- オプションでアテンション重みの可視化
詳細な文書はdocsディレクトリにあります。以下のトピックに分かれています:
| トピック | 英語版 | 日本語版 |
|---|---|---|
| クイックスタート | Quick Start Guide | クイックスタートガイド |
| モデルアーキテクチャ | Model Architecture | モデルアーキテクチャ |
| トレーニングプロセス | Training Process | トレーニングプロセス |
| 推論プロセス | Inference Process | 推論プロセス |
| キャプション生成例 | Caption Generation Examples | キャプション生成例 |
- SemArtデータセットを提供してくださったNoa Garcia氏に感謝いたします。
- インスピレーションを受けたPyTorch Image Captioningチュートリアルに感謝いたします。
- Garcia, N., & Vogiatzis, G. (2018). How to Read Paintings: Semantic Art Understanding with Multi-Modal Retrieval. Proceedings of the European Conference in Computer Vision Workshops.
このプロジェクトは教育・非商用目的でのみ使用できます。SemArtデータセットの使用に関しては、データセットの利用規約に従ってください。
