Transformers documentation

Chú thích hình ảnh

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Chú thích hình ảnh

Image captioning là nhiệm vụ dự đoán chú thích cho một hình ảnh nhất định. Các ứng dụng thực tế phổ biến của nó bao gồm hỗ trợ người khiếm thị, giúp họ di chuyển qua các tình huống khác nhau. Do đó, image captioning giúp cải thiện khả năng tiếp cận nội dung cho mọi người bằng cách mô tả hình ảnh cho họ.

Hướng dẫn này sẽ cho bạn thấy cách:

  • Tinh chỉnh một mô hình chú thích hình ảnh.
  • Sử dụng mô hình đã tinh chỉnh để suy luận.

Trước khi bắt đầu, hãy đảm bảo bạn đã cài đặt tất cả các thư viện cần thiết:

pip install transformers datasets evaluate -q
pip install jiwer -q

Chúng tôi khuyến khích bạn đăng nhập vào tài khoản Hugging Face của mình để có thể tải lên và chia sẻ mô hình của bạn với cộng đồng. Khi được yêu cầu, hãy nhập token của bạn để đăng nhập:

from huggingface_hub import notebook_login

notebook_login()

Tải bộ dữ liệu chú thích Pokémon BLIP

Sử dụng thư viện 🤗 Dataset để tải một dataset gồm các cặp {image-caption}. Để tạo dataset chú thích hình ảnh của riêng bạn trong PyTorch, bạn có thể làm theo notebook này.

from datasets import load_dataset

ds = load_dataset("lambdalabs/pokemon-blip-captions")
ds
DatasetDict({
    train: Dataset({
        features: ['image', 'text'],
        num_rows: 833
    })
})

Bộ dữ liệu có hai đặc trưng, image và text.

Nhiều bộ dữ liệu chú thích hình ảnh chứa nhiều chú thích cho mỗi hình ảnh. Trong những trường hợp đó, một chiến lược phổ biến là lấy mẫu ngẫu nhiên một chú thích trong số các chú thích có sẵn trong quá trình huấn luyện.

Chia phần train của bộ dữ liệu thành tập train và tập test bằng phương thức train_test_split:

ds = ds["train"].train_test_split(test_size=0.1)
train_ds = ds["train"]
test_ds = ds["test"]

Hãy trực quan hóa một vài mẫu từ tập huấn luyện.

from textwrap import wrap
import matplotlib.pyplot as plt
import numpy as np


def plot_images(images, captions):
    plt.figure(figsize=(20, 20))
    for i in range(len(images)):
        ax = plt.subplot(1, len(images), i + 1)
        caption = captions[i]
        caption = "\n".join(wrap(caption, 12))
        plt.title(caption)
        plt.imshow(images[i])
        plt.axis("off")


sample_images_to_visualize = [np.array(train_ds[i]["image"]) for i in range(5)]
sample_captions = [train_ds[i]["text"] for i in range(5)]
plot_images(sample_images_to_visualize, sample_captions)
Sample training images

Tiền xử lý bộ dữ liệu

Vì tập dữ liệu có hai phương thức (ảnh và văn bản), quy trình tiền xử lý sẽ tiền xử lý cả ảnh và chú thích.

Để thực hiện điều này, hãy nạp lớp processor liên quan đến mô hình mà bạn sắp tinh chỉnh.

from transformers import AutoProcessor

checkpoint = "microsoft/git-base"
processor = AutoProcessor.from_pretrained(checkpoint)

Bộ xử lý sẽ tự động tiền xử lý hình ảnh (bao gồm thay đổi kích thước và tỷ lệ pixel) và mã hóa chú thích.

def transforms(example_batch):
    images = [x for x in example_batch["image"]]
    captions = [x for x in example_batch["text"]]
    inputs = processor(images=images, text=captions, padding="max_length")
    inputs.update({"labels": inputs["input_ids"]})
    return inputs


train_ds.set_transform(transforms)
test_ds.set_transform(transforms)

Khi bộ dữ liệu đã sẵn sàng, bạn có thể thiết lập mô hình để tinh chỉnh.

Tải một mô hình cơ sở

Tải “microsoft/git-base” vào một đối tượng AutoModelForCausalLM.

from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained(checkpoint)

Đánh giá

Các mô hình chú thích hình ảnh thường được đánh giá bằng Rouge Score hoặc Word Error Rate. Trong hướng dẫn này, bạn sẽ sử dụng Word Error Rate (WER).

Chúng tôi sử dụng thư viện 🤗 Evaluate để thực hiện điều này. Để biết các hạn chế tiềm ẩn và những lưu ý khác của WER, hãy tham khảo hướng dẫn này.

from evaluate import load
import torch

wer = load("wer")


def compute_metrics(eval_pred):
    logits, labels = eval_pred
    predicted = logits.argmax(-1)
    decoded_labels = processor.batch_decode(labels, skip_special_tokens=True)
    decoded_predictions = processor.batch_decode(predicted, skip_special_tokens=True)
    wer_score = wer.compute(predictions=decoded_predictions, references=decoded_labels)
    return {"wer_score": wer_score}

Huấn luyện

Bây giờ, bạn đã sẵn sàng để bắt đầu tinh chỉnh mô hình. Bạn sẽ sử dụng 🤗 Trainer cho việc này.

Đầu tiên, xác định các đối số huấn luyện bằng TrainingArguments.

from transformers import TrainingArguments, Trainer

model_name = checkpoint.split("/")[1]

training_args = TrainingArguments(
    output_dir=f"{model_name}-pokemon",
    learning_rate=5e-5,
    num_train_epochs=50,
    fp16=True,
    per_device_train_batch_size=32,
    per_device_eval_batch_size=32,
    gradient_accumulation_steps=2,
    save_total_limit=3,
    eval_strategy="steps",
    eval_steps=50,
    save_strategy="steps",
    save_steps=50,
    logging_steps=50,
    remove_unused_columns=False,
    push_to_hub=True,
    label_names=["labels"],
    load_best_model_at_end=True,
)

Sau đó, truyền chúng cùng với các bộ dữ liệu và mô hình cho 🤗 Trainer.

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_ds,
    eval_dataset=test_ds,
    compute_metrics=compute_metrics,
)

Để bắt đầu huấn luyện, chỉ cần gọi train() trên đối tượng Trainer.

trainer.train()

Bạn sẽ thấy loss huấn luyện giảm một cách mượt mà khi quá trình huấn luyện diễn ra.

Khi quá trình huấn luyện hoàn tất, hãy chia sẻ mô hình của bạn lên Hub bằng phương thức push_to_hub() để mọi người có thể sử dụng mô hình của bạn:

trainer.push_to_hub()

Suy luận

Lấy một hình ảnh mẫu từ test_ds để kiểm tra mô hình.

from PIL import Image
import requests

url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
image = Image.open(requests.get(url, stream=True).raw)
image
Test image

Chuẩn bị hình ảnh cho mô hình.

from accelerate import Accelerator

device = Accelerator().device
inputs = processor(images=image, return_tensors="pt").to(device)
pixel_values = inputs.pixel_values

Gọi generate và giải mã các dự đoán.

generated_ids = model.generate(pixel_values=pixel_values, max_length=50)
generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(generated_caption)
a drawing of a pink and blue pokemon

Có vẻ như mô hình đã tinh chỉnh tạo ra một chú thích khá tốt!

Update on GitHub