演習:マルチモーダル分析を実践しよう
「VLMとマルチモーダル融合の技術を実際に動かしてみよう。」
田中VPoEが開発環境を開く。
「CLIPによるZero-shot分類と融合モデルの構築を実装し、画像分類モデルとの精度を比較してくれ。」
ミッション概要
Kaggle Plant Pathologyデータセットを使い、マルチモーダル分析を実践する。
前提条件
- Python 3.10+、PyTorch、transformers
- Kaggle Plant Pathologyデータセット取得済み
Mission 1: CLIPによるZero-shot分類(30分)
以下を実装せよ。
- CLIPモデルの読み込み
- 作物の病気カテゴリをテキストラベルとして定義
- テスト画像でZero-shot分類を実行
- ResNet転移学習との精度比較
解答例
from transformers import CLIPProcessor, CLIPModel
from PIL import Image
import numpy as np
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
labels = [
"a healthy plant leaf",
"a plant leaf with rust disease",
"a plant leaf with scab disease",
"a plant leaf with multiple diseases",
]
def classify_plant(image_path):
image = Image.open(image_path)
inputs = processor(text=labels, images=image, return_tensors="pt", padding=True)
outputs = model(**inputs)
probs = outputs.logits_per_image.softmax(dim=1)
return {labels[i]: round(probs[0][i].item(), 4) for i in range(len(labels))}
# テスト実行
for img in test_images[:10]:
result = classify_plant(img)
print(f"{img}: {max(result, key=result.get)}")
Mission 2: マルチモーダル融合モデル(30分)
以下を実装せよ。
- 画像特徴量(ResNet)+ テキスト特徴量(症状記述)の融合モデル
- 早期融合アーキテクチャの実装
- 学習と評価
解答例
import torch.nn as nn
from torchvision import models
class PlantDiagnosisModel(nn.Module):
def __init__(self, text_dim=768, n_classes=4):
super().__init__()
resnet = models.resnet50(pretrained=True)
self.image_encoder = nn.Sequential(*list(resnet.children())[:-1])
self.text_encoder = nn.Linear(text_dim, 256)
self.classifier = nn.Sequential(
nn.Linear(2048 + 256, 512),
nn.ReLU(), nn.Dropout(0.3),
nn.Linear(512, n_classes),
)
def forward(self, image, text_feat):
img = self.image_encoder(image).squeeze(-1).squeeze(-1)
txt = self.text_encoder(text_feat)
combined = torch.cat([img, txt], dim=1)
return self.classifier(combined)
# 学習ループ(概要)
model = PlantDiagnosisModel()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
# ... 学習・評価コード
Mission 3: 比較レポート(30分)
以下を作成せよ。
- 3手法の精度比較表(ResNet単体、CLIP Zero-shot、マルチモーダル融合)
- 各手法の強みと弱みの分析
- 業務への推奨手法と根拠
解答例
=== 比較レポート ===
| 手法 | Accuracy | F1 | 推論時間 | 学習データ |
|------|----------|-----|---------|-----------|
| ResNet転移学習 | 0.88 | 0.86 | 5ms | 必要 |
| CLIP Zero-shot | 0.72 | 0.70 | 20ms | 不要 |
| マルチモーダル融合 | 0.91 | 0.89 | 15ms | 必要 |
推奨: マルチモーダル融合(最高精度)
フォールバック: CLIP Zero-shot(新カテゴリ追加時)
ベースライン: ResNet(速度重視の場合)
達成度チェック
- CLIP Zero-shot分類を実装した
- マルチモーダル融合モデルを構築した
- 3手法の定量的比較を行った
- 業務への推奨手法を選定した
推定所要時間: 90分