用VideoMAE微调视频分类模型的流程要点

基于HuggingFace文档梳理视频分类微调的关键环节,包括从预训练检查点加载VideoMAE并随机初始化分类头、借助PyTorchVideo完成视频预处理,以及训练时关闭未用列移除以避免特征被丢弃。

Copyright 2023 HuggingFace Team. 全权保留. 根据 Apache 许可, 版本 2.0 (“ License ”) 获得许可; 您不能使用此文件, 除非符合 您可在下列地点获得许可证副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或书面同意,否则根据许可证分发的软件在下列网址分发: a " :ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,或明示的或暗示的。 《许可证》规定的许可和限制的具体语言。 ⚠️ 注意此文件在 Markdown 中, 但包含我们doc- builder(类似于 MDX ) 的特定语法, 可能不是 在您的Markdown 查看器中正确渲染。 # 视频分类 [[open-in-colab]] 视频分类是给整个视频分配标签或类的任务. 视频预计每个视频只有一个类. 视频分类模型将视频作为输入,并返回关于视频属于哪个类的预测. 这些模型可以用来对视频的全部内容进行分类.视频分类的现实应用是动作/活动识别,这对健身应用有益,对视力障碍的个人也有帮助,特别是在他们通勤时. 该指南将教你如何: 1. 微调 [VideoMAE](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/model_doc/videomae>) 在一个子集上 [UCF101](https://www.crcv.ucf.edu/data/UCF101.php) 数据集。 2. 用你精细的模型来推断 为使所有建筑和检查站都符合这项任务,我们建议检查这些建筑和检查站。 [task-page](https://huggingface.co/tasks/video-classification). 在开始前,请务必安装所有必要的库: ```bash pip install -q pytorchvideo transformers evaluate ``` 你会用 [PyTorchVideo](https://pytorchvideo.org/) (闷闷不乐) `pytorchvideo`处理和准备录像。 我们鼓励您登录您的 Hugging Face 账户, 以便您可以上传并分享您的模型。 当被提示时, 请输入您的符号以登录 : ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## 装入 UCF101 数据集 从装入子集开始 [UCF-101 数据集](https://www.crcv.ucf.edu/data/UCF101.php)这将给你一个机会来进行实验,确保一切正常运行,然后花更多的时间在完整的数据集上进行培训。 ```py >>> from huggingface_hub import hf_hub_download >>> hf_dataset_identifier = "sayakpaul/ucf101-subset" >>> filename = "UCF101_subset.tar.gz" >>> file_path = hf_hub_download(repo_id=hf_dataset_identifier, filename=filename, repo_type="dataset") ``` 子集下载后, 您需要提取压缩归档 : ```py >>> import tarfile >>> with tarfile.open(file_path) as t: ... t.extractall(".") ``` 在高层次上,数据集的结构是这样的: ```bash UCF101_subset/ train/ BandMarching/ video_1.mp4 video_2.mp4 ... Archery video_1.mp4 video_2.mp4 ... ... val/ BandMarching/ video_1.mp4 video_2.mp4 ... Archery video_1.mp4 video_2.mp4 ... ... test/ BandMarching/ video_1.mp4 video_2.mp4 ... Archery video_1.mp4 video_2.mp4 ... ... ``` 然后可以数出视频总数。 ```py >>> import pathlib >>> dataset_root_path = "UCF101_subset" >>> dataset_root_path = pathlib.Path(dataset_root_path) ``` ```py >>> video_count_train = len(list(dataset_root_path.glob("train/*/*.avi"))) >>> video_count_val = len(list(dataset_root_path.glob("val/*/*.avi"))) >>> video_count_test = len(list(dataset_root_path.glob("test/*/*.avi"))) >>> video_total = video_count_train + video_count_val + video_count_test >>> print(f"Total videos: {video_total}") ``` ```py >>> all_video_file_paths = ( ... list(dataset_root_path.glob("train/*/*.avi")) ... + list(dataset_root_path.glob("val/*/*.avi")) ... + list(dataset_root_path.glob("test/*/*.avi")) ... ) >>> all_video_file_paths[:5] ``` (a) 国家`sorted`视频路径看起来是这样的: ```bash ... 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g07_c04.avi', 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g07_c06.avi', 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g08_c01.avi', 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g09_c02.avi', 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g09_c06.avi' ... ``` 你会注意到,有些视频片段属于同一个组/场景,其中组的表示是: `g` 在视频文件路径中。 `v_ApplyEyeMakeup_g07_c04.avi` 财务报告和财务报告 `v_ApplyEyeMakeup_g07_c06.avi`比如说。 对于验证和评价的分裂,你不希望有视频片段 从同一个组/场景防止 [数据泄漏](https://www.kaggle.com/code/alexisbcook/data-leakage)。在此教程中使用的子集会考虑这些信息。 接下来,您将获取数据集中存在的一组标签。另外,创建两个字典,在初始化模型时会有所帮助: * `label2id`: 将类名称映射为整数。 * `id2label`: 将整数映射到类名称。 ```py >>> class_labels = sorted({str(path).split("/")[2] for path in all_video_file_paths}) >>> label2id = {label: i for i, label in enumerate(class_labels)} >>> id2label = {i: label for label, i in label2id.items()} >>> print(f"Unique classes: {list(label2id.keys())}.") # Unique classes: ['ApplyEyeMakeup', 'ApplyLipstick', 'Archery', 'BabyCrawling', 'BalanceBeam', 'BandMarching', 'BaseballPitch', 'Basketball', 'BasketballDunk', 'BenchPress']. ``` 有10独有的班级,每个班级都有30的视频在训练集中播放. ## 装入模型进行微调 从一个预先经过训练的检查点及其相关的图像处理器中验证一个视频分类模型,模型的编码器会带有预先经过训练的参数,分类头会随机初始化,图像处理器在为我们的数据集写入预处理管道时会有所帮助. ```py >>> from transformers import VideoMAEImageProcessor, VideoMAEForVideoClassification >>> model_ckpt = "MCG-NJU/videomae-base" >>> image_processor = VideoMAEImageProcessor.from_pretrained(model_ckpt) >>> model = VideoMAEForVideoClassification.from_pretrained( ... model_ckpt, ... label2id=label2id, ... id2label=id2label, ... ignore_mismatched_sizes=True, # provide this in case you're planning to fine-tune an already fine-tuned checkpoint ... ) ``` 当模型装入时,你可能会注意到以下警告: ```bash Some weights of the model checkpoint at MCG-NJU/videomae-base were not used when initializing VideoMAEForVideoClassification: [..., 'decoder.decoder_layers.1.attention.output.dense.bias', 'decoder.decoder_layers.2.attention.attention.key.weight'] - This IS expected if you are initializing VideoMAEForVideoClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model). - This IS NOT expected if you are initializing VideoMAEForVideoClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model). Some weights of VideoMAEForVideoClassification were not initialized from the model checkpoint at MCG-NJU/videomae-base and are newly initialized: ['classifier.bias', 'classifier.weight'] You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference. ``` 警告告诉我们,我们正在丢掉一些重量(例如,这些重量和偏重)。 `classifier` 并随机初始化一些其他的(新加的重量和偏差) `classifier` 这在本案中是预料到的,因为我们正在增加一个新的头,我们没有经过预先训练的重量,所以图书馆警告我们,在使用这个模型进行推论之前,我们应该对其进行微调,这正是我们要做的事情。 **说明** 那个 [这个检查站](https://huggingface.co/MCG-NJU/videomae-base-finetuned-kinetics) 由于检查站在类似下游任务上得到了微调,而且域内重叠很大,因此,这项工作的业绩得到改善。 ## 编制培训数据集 为了预处理视频,你会利用 [PyTorchVideo 库](https://pytorchvideo.org/)。从导入我们需要的依赖开始。 ```py >>> import pytorchvideo.data >>> from pytorchvideo.transforms import ( ... ApplyTransformToKey, ... Normalize, ... RandomShortSideScale, ... RemoveKey, ... ShortSideScale, ... UniformTemporalSubsample, ... ) >>> from torchvision.transforms import ( ... Compose, ... Lambda, ... RandomCrop, ... RandomHorizontalFlip, ... Resize, ... ) ``` 对于训练数据集的转换,采用统一的时间分样、像素正常化、随机裁剪和随机水平翻转的组合。对于验证和评价数据集的转换,除了随机裁剪和横向翻转外,要保持相同的转换链。要更多地了解这些转换的细节,请检查 [PyTorchVideo的正式文件](https://pytorchvideo.org). 使用该 `image_processor` 与预训模式有关,以获得以下信息: * 图像平均与标准偏差, 视频帧像素将与之正常化 。 * 空间分辨率,视频帧将调整为这个分辨率。 从定义一些常数开始. ```py >>> mean = image_processor.image_mean >>> std = image_processor.image_std >>> if "shortest_edge" in image_processor.size: ... height = width = image_processor.size["shortest_edge"] >>> else: ... height = image_processor.size["height"] ... width = image_processor.size["width"] >>> resize_to = (height, width) >>> num_frames_to_sample = model.config.num_frames >>> sample_rate = 4 >>> fps = 30 >>> clip_duration = num_frames_to_sample * sample_rate / fps ``` 现在,分别定义数据集特定变换和数据集。从培训组开始: ```py >>> train_transform = Compose( ... [ ... ApplyTransformToKey( ... key="video", ... transform=Compose( ... [ ... UniformTemporalSubsample(num_frames_to_sample), ... Lambda(lambda x: x / 255.0), ... Normalize(mean, std), ... RandomShortSideScale(min_size=256, max_size=320), ... RandomCrop(resize_to), ... RandomHorizontalFlip(p=0.5), ... ] ... ), ... ), ... ] ... ) >>> train_dataset = pytorchvideo.data.Ucf101( ... data_path=os.path.join(dataset_root_path, "train"), ... clip_sampler=pytorchvideo.data.make_clip_sampler("random", clip_duration), ... decode_audio=False, ... transform=train_transform, ... ) ``` 同样的工作流程序列可以适用于验证和评价组: ```py >>> val_transform = Compose( ... [ ... ApplyTransformToKey( ... key="video", ... transform=Compose( ... [ ... UniformTemporalSubsample(num_frames_to_sample), ... Lambda(lambda x: x / 255.0), ... Normalize(mean, std), ... Resize(resize_to), ... ] ... ), ... ), ... ] ... ) >>> val_dataset = pytorchvideo.data.Ucf101( ... data_path=os.path.join(dataset_root_path, "val"), ... clip_sampler=pytorchvideo.data.make_clip_sampler("uniform", clip_duration), ... decode_audio=False, ... transform=val_transform, ... ) >>> test_dataset = pytorchvideo.data.Ucf101( ... data_path=os.path.join(dataset_root_path, "test"), ... clip_sampler=pytorchvideo.data.make_clip_sampler("uniform", clip_duration), ... decode_audio=False, ... transform=val_transform, ... ) ``` **说明**: 上述数据集管道取自 [官方 PyTorchVideo 实例](https://pytorchvideo.org/docs/tutorial_classification#dataset)我们用的是 [`pytorchvideo.data.Ucf101()`](https://pytorchvideo.readthedocs.io/en/latest/api/data/data.html#pytorchvideo.data.Ucf101) 函数,因为它是专门为 UCF-101 数据集设计的。在引擎盖下,它返回 a [`pytorchvideo.data.labeled_video_dataset.LabeledVideoDataset`](https://pytorchvideo.readthedocs.io/en/latest/api/data/data.html#pytorchvideo.data.LabeledVideoDataset) 对象。 `LabeledVideoDataset` 类是 PyTorchVideo 数据集中所有事项的基类。所以,如果您想要使用一个自定义数据集,而不用 off-the-shelf 支持 PyTorchVideo ,您可以扩展 `LabeledVideoDataset` 相应类别。 `data` API [文档到](https://pytorchvideo.readthedocs.io/en/latest/api/data/data.html) 另外,如果数据集遵循类似的结构(如上所示),则使用 `pytorchvideo.data.Ucf101()` 工作应该很好 你可以访问 `num_videos` 参数以了解数据集中的视频数量。 ```py >>> print(train_dataset.num_videos, val_dataset.num_videos, test_dataset.num_videos) # (300, 30, 75) ``` ## 可视化预处理的视频以更好地调试 ```py >>> import imageio >>> import numpy as np >>> from IPython.display import Image >>> def unnormalize_img(img): ... """Un-normalizes the image pixels.""" ... img = (img * std) + mean ... img = (img * 255).astype("uint8") ... return img.clip(0, 255) >>> def create_gif(video_tensor, filename="sample.gif"): ... """Prepares a GIF from a video tensor. ... ... The video tensor is expected to have the following shape: ... (num_frames, num_channels, height, width). ... """ ... frames = [] ... for video_frame in video_tensor: ... frame_unnormalized = unnormalize_img(video_frame.permute(1, 2, 0).numpy()) ... frames.append(frame_unnormalized) ... kargs = {"duration": 0.25} ... imageio.mimsave(filename, frames, "GIF", **kargs) ... return filename >>> def display_gif(video_tensor, gif_name="sample.gif"): ... """Prepares and displays a GIF from a video tensor.""" ... video_tensor = video_tensor.permute(1, 0, 2, 3) ... gif_filename = create_gif(video_tensor, gif_name) ... return Image(filename=gif_filename) >>> sample_video = next(iter(train_dataset)) >>> video_tensor = sample_video["video"] >>> display_gif(video_tensor) ``` <img src=' https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/sample_gif.gif" alt="个人打篮球"/> ## 训练模型 借阅 [`Trainer`] 从 QQ Transformers 用于训练模型。 `Trainer`,您需要定义培训配置和评价衡量标准。最重要的是 [`TrainingArguments`],这是一个包含所有配置培训的属性的类。它需要一个输出文件夹名称,用于保存模型的检查点。它也有助于同步模型库中QQ Hub上的所有信息。 大多数培训论点不言自明,但其中很重要的一点是: `remove_unused_columns=False`。这个将删除模型的调用函数没有使用的任何特性。默认是 `True` 因为通常最理想的做法是放下未使用的功能列, 从而更容易解开输入到模型的调用功能中。 但是, 在这种情况下, 您需要未使用的功能( 特别是“ video” ) 才能创建 。 `pixel_values` (这是我们模式在投入中期望的强制性关键). ```py >>> from transformers import TrainingArguments, Trainer >>> model_name = model_ckpt.split("/")[-1] >>> new_model_name = f"{model_name}-finetuned-ucf101-subset" >>> num_epochs = 4 >>> args = TrainingArguments( ... new_model_name, ... remove_unused_columns=False, ... eval_strategy="epoch", ... save_strategy="epoch", ... learning_rate=5e-5, ... per_device_train_batch_size=batch_size, ... per_device_eval_batch_size=batch_size, ... warmup_steps=0.1, ... logging_steps=10, ... load_best_model_at_end=True, ... metric_for_best_model="accuracy", ... push_to_hub=True, ... max_steps=(train_dataset.num_videos // batch_size) * num_epochs, ... ) ``` 返回的数据集由 `pytorchvideo.data.Ucf101()` 不执行 `__len__` 因此,我们必须界定 `max_steps` 当瞬间 `TrainingArguments`. 接下来,您需要定义一个函数来从预测中计算度量,该函数将使用 `metric` 唯一需要做的预处理是使用我们预测的对数的正格 : ```py import evaluate metric = evaluate.load("accuracy") def compute_metrics(eval_pred): predictions = np.argmax(eval_pred.predictions, axis=1) return metric.compute(predictions=predictions, references=eval_pred.label_ids) ``` **关于评价的说明**: 在那个 [VideoMAE 纸张](https://huggingface.co/papers/2203.12602),作者使用以下评价策略。他们从测试视频中用几个片段来评价模型,并将不同的作物应用于这些片段,并报告总分。然而,为了简洁简洁起见,我们在此教程中不考虑这一点。 此外,定义a `collate_fn`,用于将示例组合在一起。每个批次由 2 密钥组成,即 `pixel_values` 财务报告和财务报告 `labels`. ```py >>> def collate_fn(examples): ... # permute to (num_frames, num_channels, height, width) ... pixel_values = torch.stack( ... [example["video"].permute(1, 0, 2, 3) for example in examples] ... ) ... labels = torch.tensor([example["label"] for example in examples]) ... return {"pixel_values": pixel_values, "labels": labels} ``` 然后,你只是传递这一切 与数据集 `Trainer`: ```py >>> trainer = Trainer( ... model, ... args, ... train_dataset=train_dataset, ... eval_dataset=val_dataset, ... processing_class=image_processor, ... compute_metrics=compute_metrics, ... data_collator=collate_fn, ... ) ``` 你可能想知道你为什么沿着 `image_processor` 当您在预处理数据时, 它只是要保证图像处理器配置文件( 存储为 JSON ) 也将上传到 Hub 上的重播 。 现在,微调我们的模型 通过呼叫 `train` 方法 : ```py >>> train_results = trainer.train() ``` 训练完成后,将你的模型与Hub分享 [`~transformers.Trainer.push_to_hub`] 方法让每个人都可以使用你的模型: ```py >>> trainer.push_to_hub() ``` ## 推论 好极了,现在你对一个模型做了精细的调整, 你可以用它来推论! 装入视频进行推断 : ```py >>> sample_test_video = next(iter(test_dataset)) ``` <img src=' https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/sample_gif_two.gif" alt="打篮球的队伍"/> 最简单的方法 测试你的微调模型 推论是用在一个 [`VideoClassificationPipeline`]说明a `pipeline` 与你的模型进行视频分类, 将您的视频传递给它: ```py >>> from transformers import pipeline from accelerate import Accelerator >>> video_cls = pipeline(model="my_awesome_video_cls_model") >>> video_cls("https://huggingface.co/datasets/sayakpaul/ucf101-subset/resolve/main/v_BasketballDunk_g14_c06.avi") [{'score': 0.9272987842559814, 'label': 'BasketballDunk'}, {'score': 0.017777055501937866, 'label': 'BabyCrawling'}, {'score': 0.01663011871278286, 'label': 'BalanceBeam'}, {'score': 0.009560945443809032, 'label': 'BandMarching'}, {'score': 0.0068979403004050255, 'label': 'BaseballPitch'}] ``` 您也可以手动复制该程序的结果 `pipeline` 如果你愿意的话。 ```py >>> def run_inference(model, video): ... # (num_frames, num_channels, height, width) ... permuted_sample_test_video = video.permute(1, 0, 2, 3) ... inputs = { ... "pixel_values": perumuted_sample_test_video.unsqueeze(0), ... "labels": torch.tensor( ... [sample_test_video["label"]] ... ), # this can be skipped if you don't have labels available. ... } ... device = Accelerator().device ... inputs = {k: v.to(device) for k, v in inputs.items()} ... model = model.to(device) ... # forward pass ... with torch.no_grad(): ... outputs = model(**inputs) ... logits = outputs.logits ... return logits ``` 现在,把你的输入 给模型,并返回 `logits`: ```py >>> logits = run_inference(trained_model, sample_test_video["video"]) ``` 解码 `logits`,我们得到: ```py >>> predicted_class_idx = logits.argmax(-1).item() >>> print("Predicted class:", model.config.id2label[predicted_class_idx]) # Predicted class: BasketballDunk ```

查看原始来源