| # Penyebutan gambar | |
| Image captioning adalah tugas memprediksi caption untuk gambar tertentu. Aplikasi dunia nyata yang umum meliputi membantu orang tunanetra agar dapat menavigasi berbagai situasi. Oleh karena itu, image captioning membantu meningkatkan aksesibilitas konten bagi orang-orang dengan cara mendeskripsikan gambar kepada mereka. | |
| Panduan ini akan menunjukkan cara Anda untuk: | |
| * Lakukan fine-tuning pada model captioning gambar. | |
| * Gunakan model yang telah dihaluskan untuk inferensi. | |
| Sebelum memulai, pastikan Anda telah menginstal semua pustaka yang diperlukan: | |
| ```bash | |
| pip install transformers datasets evaluate -q | |
| pip install jiwer -q | |
| ``` | |
| Kami menyarankan Anda untuk masuk ke akun Hugging Face Anda agar dapat mengunggah dan membagikan model Anda dengan komunitas. Saat diminta, masukkan token Anda untuk masuk: | |
| ```python | |
| from huggingface_hub import notebook_login | |
| notebook_login() | |
| ``` | |
| ## Muat dataset caption Pokémon BLIP | |
| Gunakan pustaka 🤗 Dataset untuk memuat dataset yang terdiri dari pasangan {image-caption}. Untuk membuat dataset captioning gambar Anda sendiri di PyTorch, Anda dapat mengikuti [notebook ini](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/GIT/Fine_tune_GIT_on_an_image_captioning_dataset.ipynb). | |
| ```python | |
| from datasets import load_dataset | |
| ds = load_dataset("lambdalabs/pokemon-blip-captions") | |
| ds | |
| ``` | |
| ```bash | |
| DatasetDict({ | |
| train: Dataset({ | |
| features: ['image', 'text'], | |
| num_rows: 833 | |
| }) | |
| }) | |
| ``` | |
| Dataset memiliki dua fitur, `image` dan `text`. | |
| Banyak dataset captioning gambar berisi beberapa caption untuk setiap gambar. Dalam kasus tersebut, strategi yang umum digunakan adalah mengambil sampel secara acak dari caption yang tersedia selama pelatihan. | |
| Bagi split train dari dataset menjadi set train dan test dengan metode [train_test_split](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.train_test_split): | |
| ```python | |
| ds = ds["train"].train_test_split(test_size=0.1) | |
| train_ds = ds["train"] | |
| test_ds = ds["test"] | |
| ``` | |
| Mari kita visualisasi beberapa sampel dari set pelatihan. | |
| ```python | |
| 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) | |
| ``` | |
| ## Praproses dataset | |
| Karena dataset memiliki dua modalitas (gambar dan teks), pipeline pra-pemrosesan akan memproses gambar dan caption. | |
| Untuk melakukannya, muat kelas processor yang terkait dengan model yang akan Anda fine-tune. | |
| ```python | |
| from transformers import AutoProcessor | |
| checkpoint = "microsoft/git-base" | |
| processor = AutoProcessor.from_pretrained(checkpoint) | |
| ``` | |
| Processor akan memproses praproses gambar secara internal (termasuk pengubahan ukuran dan penskalaan piksel) serta melakukan tokenisasi pada caption. | |
| ```python | |
| 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) | |
| ``` | |
| Dengan dataset yang sudah siap, Anda sekarang dapat menyiapkan model untuk fine-tuning. | |
| ## Muat model dasar | |
| Muat ["microsoft/git-base"](https://huggingface.co/microsoft/git-base) ke dalam objek [AutoModelForCausalLM](/docs/transformers/main/id/model_doc/auto#transformers.AutoModelForCausalLM). | |
| ```python | |
| from transformers import AutoModelForCausalLM | |
| model = AutoModelForCausalLM.from_pretrained(checkpoint) | |
| ``` | |
| ## Evaluasi | |
| Model captioning gambar biasanya dievaluasi menggunakan [Rouge Score](https://huggingface.co/spaces/evaluate-metric/rouge) atau [Word Error Rate](https://huggingface.co/spaces/evaluate-metric/wer). Untuk panduan ini, Anda akan menggunakan Word Error Rate (WER). | |
| Kami menggunakan pustaka 🤗 Evaluate untuk melakukannya. Untuk potensi keterbatasan dan hal-hal lain yang perlu diperhatikan terkait WER, silakan merujuk ke [panduan ini](https://huggingface.co/spaces/evaluate-metric/wer). | |
| ```python | |
| 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} | |
| ``` | |
| ## Latih | |
| Sekarang, Anda siap untuk mulai melakukan fine-tuning pada model. Anda akan menggunakan 🤗 [Trainer](/docs/transformers/main/id/main_classes/trainer#transformers.Trainer) untuk ini. | |
| Pertama, definisikan argumen pelatihan menggunakan [TrainingArguments](/docs/transformers/main/id/main_classes/trainer#transformers.TrainingArguments). | |
| ```python | |
| 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, | |
| ) | |
| ``` | |
| Lalu, teruskan bersama dataset dan model ke 🤗 Trainer. | |
| ```python | |
| trainer = Trainer( | |
| model=model, | |
| args=training_args, | |
| train_dataset=train_ds, | |
| eval_dataset=test_ds, | |
| compute_metrics=compute_metrics, | |
| ) | |
| ``` | |
| Untuk memulai pelatihan, cukup panggil [train()](/docs/transformers/main/id/main_classes/trainer#transformers.Trainer.train) pada objek [Trainer](/docs/transformers/main/id/main_classes/trainer#transformers.Trainer). | |
| ```python | |
| trainer.train() | |
| ``` | |
| Anda seharusnya melihat penurunan loss pelatihan secara mulus seiring berjalannya pelatihan. | |
| Setelah pelatihan selesai, bagikan model Anda ke Hub dengan metode [push_to_hub()](/docs/transformers/main/id/main_classes/trainer#transformers.Trainer.push_to_hub) agar semua orang dapat menggunakan model Anda: | |
| ```python | |
| trainer.push_to_hub() | |
| ``` | |
| ## Inferensi | |
| Ambil gambar sampel dari `test_ds` untuk menguji model. | |
| ```python | |
| 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 | |
| ``` | |
| Siapkan gambar untuk model. | |
| ```python | |
| from accelerate import Accelerator | |
| device = Accelerator().device | |
| inputs = processor(images=image, return_tensors="pt").to(device) | |
| pixel_values = inputs.pixel_values | |
| ``` | |
| Panggil `generate` dan decode prediksi. | |
| ```python | |
| 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) | |
| ``` | |
| ```bash | |
| a drawing of a pink and blue pokemon | |
| ``` | |
| Sepertinya model yang telah dihaluskan menghasilkan caption yang cukup bagus! | |
Xet Storage Details
- Size:
- 7.63 kB
- Xet hash:
- 554c400d302ef4dca0658ce993a78520b43a610ca5405ce8f6812bbfae63e5d4
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.