尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

Transformers 图像描述实战:基于 GIT 与 Pokémon BLIP 数据集完成微调与推理

Transformers 图像描述实战:基于 GIT 与 Pokémon BLIP 数据集完成微调与推理 Transformers 图像描述实战基于 GIT 与 Pokémon BLIP 数据集完成微调与推理【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers本文以 Transformers 官方任务指南为骨架完整讲解图像描述Image Captioning任务从数据集加载、预处理、模型微调到推理的端到端流程。指南以microsoft/git-base为基座模型、lambdalabs/pokemon-blip-captions为训练数据训练完成后即可用Trainer训练出的模型对任意图片生成自然语言描述。读完本文你将掌握图像描述任务的完整数据管线、GIT 模型的加载方式、基于 WER 的评估方法以及generate推理的调用方式并了解这些操作在仓库源码中的实现位置。任务背景与前置准备图像描述Image Captioning是预测给定图片自然语言描述的任务典型现实应用包括帮助视障人士理解画面内容、提升内容的可访问性等。因此图像描述模型需要同时理解视觉模态与文本模态。开始之前请确保已安装必要的库pip install transformers datasets evaluate -q pip install jiwer -q其中jiwer用于计算 Word Error RateWER评估指标evaluate是 Evaluate 评估库datasets用于加载和预处理数据集。如果你希望将训练好的模型上传共享给社区建议先登录 Hugging Face 账号from huggingface_hub import notebook_login notebook_login()按提示输入 token 即可完成登录Trainer在设置了push_to_hubTrue后会自动将模型推送至 Hub。加载 Pokémon BLIP 图像描述数据集使用 Datasets 库加载由 {image, caption} 配对组成的数据集。本指南使用lambdalabs/pokemon-blip-captionsPokémon 图片及其 BLIP 生成的描述也可以参考该数据集的创建方式构建自己的图像描述数据集。from datasets import load_dataset ds load_dataset(lambdalabs/pokemon-blip-captions) ds输出如下DatasetDict({ train: Dataset({ features: [image, text], num_rows: 833 }) })数据集包含image和text两个特征image为图片像素数据text为对应的描述文本。833 行数据中全部位于 train 分区。提示许多图像描述数据集为每张图片提供多条候选描述。这种情况下常见的训练策略是每次训练时从可用描述中随机采样一条以增强模型的泛化能力。接着用train_test_split方法将训练集按 10% 比例划分为训练集和测试集ds ds[train].train_test_split(test_size0.1) train_ds ds[train] test_ds ds[test]可视化训练集中的若干样本便于直观理解数据内容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)数据预处理图像与文本的双模态管线由于数据集包含图像和文本两种模态预处理管线需要同时处理二者。做法是加载与待微调模型关联的 processor 类from transformers import AutoProcessor checkpoint microsoft/git-base processor AutoProcessor.from_pretrained(checkpoint)processor 内部会完成图像的预处理包括尺寸调整、像素缩放与描述的 tokenize。在仓库源码中GIT 对应的 processor 为GitProcessor它继承自ProcessorMixin本质上是图像处理器 分词器的组合体因此AutoProcessor.from_pretrained会自动加载配套的GitImageProcessor负责 resize、像素缩放和BertTokenizer负责文本 tokenize。定义数据变换函数将图像和文本统一转换为模型输入def transforms(example_batch): images [x for x in example_batch[image]] captions [x for x in example_batch[text]] inputs processor(imagesimages, textcaptions, paddingmax_length) inputs.update({labels: inputs[input_ids]}) return inputs train_ds.set_transform(transforms) test_ds.set_transform(transforms)这里有两个关键点processor(images..., text..., paddingmax_length)返回的input_ids即描述文本的 token 序列同时内部会对图像做尺寸调整GIT 默认输入为 224×224与像素归一化labels直接复用input_ids用于计算自回归语言建模损失next token prediction。这与GitForCausalLM.forward中labels的语义一致——标签为(batch_size, sequence_length)的 token 索引token 值为-100的位置会被忽略见 modeling_git.py。数据集就绪后即可进入模型微调阶段。加载基座模型将microsoft/git-base加载为AutoModelForCausalLM对象from transformers import AutoModelForCausalLM model AutoModelForCausalLM.from_pretrained(checkpoint)从源码看仓库的自动映射表已将模型类型git映射到GitForCausalLM见 modeling_auto.py。GitForCausalLM由GitModel视觉编码器 文本 Transformer与一个nn.Linear(config.hidden_size, config.vocab_size)输出层组成并继承GenerationMixin因此天然支持generate自回归生成。GIT 的结构可以从配置类中得到印证见 configuration_git.pyGitVisionConfig视觉编码器配置默认image_size224、patch_size16、12 层 Transformer、hidden size 768GitConfig整体配置默认vocab_size30522、6 层文本 Transformer、max_position_embeddings1024并内嵌vision_config子配置num_image_with_embedding参数用于视频描述/VQA 场景追加时间嵌入。评估使用 Word Error Rate图像描述模型通常使用 Rouge Score 或 Word Error RateWER评估。本指南采用 WER。使用 Evaluate 库实现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_tokensTrue) decoded_predictions processor.batch_decode(predicted, skip_special_tokensTrue) wer_score wer.compute(predictionsdecoded_predictions, referencesdecoded_labels) return {wer_score: wer_score}compute_metrics在Trainer每次评估时被调用logits.argmax(-1)取每个位置概率最大的 token id随后用 processor 的batch_decode(..., skip_special_tokensTrue)将 id 序列解码为文本跳过[CLS]、[SEP]、[PAD]等特殊 token最后与参考文本计算 WER。WER 的潜在局限与注意事项可参考其指标说明如对同义词、词序变化的敏感性。微调训练使用 Trainer完成微调。首先通过TrainingArguments定义训练参数from transformers import TrainingArguments, Trainer model_name checkpoint.split(/)[1] training_args TrainingArguments( output_dirf{model_name}-pokemon, learning_rate5e-5, num_train_epochs50, fp16True, per_device_train_batch_size32, per_device_eval_batch_size32, gradient_accumulation_steps2, save_total_limit3, eval_strategysteps, eval_steps50, save_strategysteps, save_steps50, logging_steps50, remove_unused_columnsFalse, push_to_hubTrue, label_names[labels], load_best_model_at_endTrue, )各参数含义与配置要点参数取值说明output_dirgit-base-pokemon模型检查点输出目录由model_name拼接而来learning_rate5e-5峰值学习率num_train_epochs50训练轮数Pokémon 数据集规模小需较多 epoch 收敛fp16True启用混合精度训练需 GPU 支持无 GPU 时应设为Falseper_device_train/eval_batch_size32单设备 batch 大小需根据显存调整gradient_accumulation_steps2梯度累积步数等效放大 batch 为 64save_total_limit3最多保留 3 个检查点防止磁盘膨胀eval_strategy/eval_stepssteps/50每 50 步评估一次save_strategy/save_stepssteps/50每 50 步保存一次检查点logging_steps50每 50 步记录一次日志remove_unused_columnsFalse关键保留原始image列等非模型输入列供自定义transforms使用push_to_hubTrue训练后自动推送模型到 Hub需已登录label_names[labels]显式指定标签列名配合load_best_model_at_end在结束时加载最优检查点然后将模型、数据集与评估函数一起交给Trainertrainer Trainer( modelmodel, argstraining_args, train_datasettrain_ds, eval_datasettest_ds, compute_metricscompute_metrics, )启动训练trainer.train()训练过程中可观察到训练损失平滑下降。训练完成后用push_to_hub将模型共享到 Hub方便社区直接使用trainer.push_to_hub()推理生成图像描述从test_ds取一张样本图片测试模型from PIL import Image import requests url https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png image Image.open(requests.get(url, streamTrue).raw) image为模型准备图像输入from accelerate import Accelerator device Accelerator().device inputs processor(imagesimage, return_tensorspt).to(device) pixel_values inputs.pixel_values这里使用Accelerator().device自动选择 GPU/CPU 设备。processor 输出的pixel_values即为 GIT 视觉编码器的输入张量——与源码中GitForCausalLM.forward的pixel_values参数对应见 modeling_git.py。调用generate解码预测结果generated_ids model.generate(pixel_valuespixel_values, max_length50) generated_caption processor.batch_decode(generated_ids, skip_special_tokensTrue)[0] print(generated_caption)输出示例a drawing of a pink and blue pokemon微调后的模型生成的描述质量相当不错。generate由GenerationMixin提供max_length50限制生成的最大 token 数生成的 id 序列经batch_decode去掉特殊 token 后即为最终描述文本。值得注意的是同样的GitForCausalLM模型在仓库的源码 docstring 中还展示了两个相关用法见 modeling_git.pyVQA视觉问答传入pixel_values的同时将问题文本 tokenize 后以input_ids传入generate即可让模型根据图片回答问题视频描述加载microsoft/git-base-vatex检查点配合num_image_with_embedding时间嵌入处理多帧输入。这体现了 GIT 架构视觉编码器 因果语言模型的通用性同一套微调流程稍作改动即可迁移到不同多模态生成任务。小结本文完整复现了图像描述任务的端到端流程加载并划分pokemon-blip-captions数据集 → 用AutoProcessor构建图像 文本双模态预处理管线 → 加载microsoft/git-base为AutoModelForCausalLM→ 以 WER 为评估指标、Trainer完成 50 个 epoch 的微调 → 用generate对新图片生成描述。对应的全部实现细节均可在仓库的 GIT 模型目录 中找到GitProcessor组合了图像处理器与分词器GitConfig/GitVisionConfig定义了双模态配置GitForCausalLM则基于GenerationMixin提供统一的生成入口。这套方法论不仅适用于图像描述稍加改动即可扩展到 VQA、视频描述等更多多模态任务。【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表