日本語の画像キャプション生成モデル(ViT + BERT,旧版)
画像を入力すると,その内容を表す日本語の文(キャプション)を生成するモデルです.画像のエンコーダに ViT,文のデコーダに日本語の BERT を使い,STAIR Captions で学習しました.2023年に作った最初の版です.
An earlier (2023) Japanese image captioning model with a ViT encoder and a Japanese BERT decoder, trained on STAIR Captions. For new uses, the GPT-2 based pipeline version is easier to use.
新しく使う場合は,後から作った GPT-2 版の fujie_vit-gpt2-japanese-image-captioning_stair-captions-pipeline の方が手軽です(トークナイザなども同梱しています).
使い方
このリポジトリにはモデルの重みしか入っていません.トークナイザ(MeCab を使うので pip install fugashi unidic-lite が必要)と画像の前処理はベースモデルから読み込みます.
import requests
from PIL import Image
from transformers import BertJapaneseTokenizer, ViTImageProcessor, VisionEncoderDecoderModel
model = VisionEncoderDecoderModel.from_pretrained(
"fujie/fujie_vit-bert-japanese-image-captioning_stair-captions-results"
)
tokenizer = BertJapaneseTokenizer.from_pretrained("cl-tohoku/bert-base-japanese-whole-word-masking")
image_processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
pixel_values = image_processor(image, return_tensors="pt").pixel_values
generated_ids = model.generate(pixel_values, max_new_tokens=30, num_beams=5)
# 出力は単語ごとに空白で区切られるので,空白を取り除く
for text in tokenizer.batch_decode(generated_ids, skip_special_tokens=True):
print(text.replace(" ", ""))
学習の方法
- 学習データ: MS-COCO の train2014 の画像と,それに日本語のキャプションを付けた STAIR Captions
- エンコーダ: google/vit-base-patch16-224-in21k
- デコーダ: cl-tohoku/bert-base-japanese-whole-word-masking
VisionEncoderDecoderModel.from_encoder_decoder_pretrained()で2つをつなぎ,Hugging Face のTrainerで全体を学習(5エポック,バッチサイズ 10,ウォームアップ 500ステップ,weight decay 0.01,キャプションの最大長 128トークン)
制約
- 学習データは MS-COCO の写真(日常の風景や物体)です.それと性質の違う画像では,的外れなキャプションになります.
- 生成されるキャプションの誤りや偏りは確認していません.
ライセンス
デコーダの cl-tohoku/bert-base-japanese-whole-word-masking のライセンス(CC BY-SA 4.0)に合わせて CC BY-SA 4.0 とします.STAIR Captions と MS-COCO のアノテーションは CC BY 4.0,google/vit-base-patch16-224-in21k は Apache 2.0 です.
作成者
藤江真也(千葉工業大学 先進工学部 未来ロボティクス学科,藤江研究室)