当前位置: 首页 > news >正文

【人工智能】Transformers之Pipeline(十):视频分类(video-classification)

目录

一、引言 

二、视频分类(video-classification)

2.1 概述

2.2 技术原理

2.3 应用场景

2.4 pipeline参数

2.4.1 pipeline对象实例化参数

2.4.2 pipeline对象使用参数 

2.4 pipeline实战

2.5 模型排名

三、总结


一、引言 

 pipeline(管道)是huggingface transformers库中一种极简方式使用大模型推理的抽象,将所有大模型分为音频(Audio)、计算机视觉(Computer vision)、自然语言处理(NLP)、多模态(Multimodal)等4大类,28小类任务(tasks)。共计覆盖32万个模型

今天介绍CV计算机视觉的第六篇:视频分类(video-classification),在huggingface库内有1100个视频分类模型。

二、视频分类(video-classification)

2.1 概述

视频分类是为整个视频分配标签或类别的任务。每个视频预计只有一个类别。视频分类模型将视频作为输入,并返回关于该视频属于哪个类别的预测。

2.2 技术原理

视频分类(video-classification)最典型的模型莫过于微软的xclip系列,xclip为clip模型的拓展,采用(视频-文本)进行对比学习训练。微软提供了包括microsoft/xclip-base-patch32、microsoft/xclip-base-patch16等不同块分辨率训练的模型。比如microsoft/xclip-base-patch32,块分辨率大小为32,使用每段视频 8 帧进行训练,分辨率为 224x224。详细论文可参考《Expanding Language-Image Pretrained Models for General Video Recognition》

2.3 应用场景

  • 内容审查与过滤:自动识别视频内容,过滤非法、暴力、成人内容,确保平台合规。
  • 视频检索:用户可以通过分类标签快速找到感兴趣的视频,提高检索效率。
  • 教育与培训:将教育视频按科目、难度等分类,便于学习者系统学习。
  • 娱乐与直播:分类管理直播内容,如游戏、音乐、生活等,便于观众选择观看。
  • 体育赛事分析:通过分类快速定位到特定比赛类型或运动员表现分析。

2.4 pipeline参数

2.4.1 pipeline对象实例化参数

  • model(PreTrainedModel或TFPreTrainedModel)— 管道将使用其进行预测的模型。 对于 PyTorch,这需要从PreTrainedModel继承;对于 TensorFlow,这需要从TFPreTrainedModel继承。
  • image_processor ( BaseImageProcessor ) — 管道将使用的图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor。
  • modelcardstrModelCard可选) — 属于此管道模型的模型卡。
  • frameworkstr可选)— 要使用的框架,"pt"适用于 PyTorch 或"tf"TensorFlow。必须安装指定的框架。
  • taskstr,默认为"")— 管道的任务标识符。
  • num_workersint可选,默认为 8)— 当管道将使用DataLoader(传递数据集时,在 Pytorch 模型的 GPU 上)时,要使用的工作者数量。
  • batch_sizeint可选,默认为 1)— 当管道将使用DataLoader(传递数据集时,在 Pytorch 模型的 GPU 上)时,要使用的批次的大小,对于推理来说,这并不总是有益的,请阅读使用管道进行批处理。
  • args_parser(ArgumentHandler,可选) - 引用负责解析提供的管道参数的对象。
  • deviceint可选,默认为 -1)— CPU/GPU 支持的设备序号。将其设置为 -1 将利用 CPU,设置为正数将在关联的 CUDA 设备 ID 上运行模型。您可以传递本机torch.devicestr
  • torch_dtypestrtorch.dtype可选) - 直接发送model_kwargs(只是一种更简单的快捷方式)以使用此模型的可用精度(torch.float16,,torch.bfloat16...或"auto"
  • binary_outputbool可选,默认为False)——标志指示管道的输出是否应以序列化格式(即 pickle)或原始输出数据(例如文本)进行。

2.4.2 pipeline对象使用参数 

  • videostrList[str])——管道处理三种类型的视频:
    • 包含指向视频的 http 链接的字符串
    • 包含视频本地路径的字符串

    管道可以接受单个视频或一批视频,然后必须将其作为字符串传递。一批视频必须全部采用相同的格式:全部为 http 链接或全部为本地路径。

  • top_kint可选,默认为 5)— 管道将返回的顶部标签数。如果提供的数字高于模型配置中可用的标签数,则将默认为标签数。
  • num_framesint可选,默认为self.model.config.num_frames)— 从视频中采样的用于运行分类的帧数。如果未提供,则默认为模型配置中指定的帧数。
  • frame_sampling_rate ( int可选,默认为 1) — 用于从视频中选择帧的采样率。如果未提供,则默认为 1,即将使用每一帧。

2.4 pipeline实战

使用hf_hub_download下载或使用本地视频:

亲测pipeline不能用,于是使用Auto模型方法,与使用Autotokenizer处理文本不同,对于图片的处理使用AutoImageProcessor(处理视频的本质就是先将视频拆帧成图片,再对图片进行处理)

import os
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"import av
import torch
import numpy as npfrom transformers import AutoImageProcessor, VideoMAEForVideoClassification,TimesformerForVideoClassification
from huggingface_hub import hf_hub_downloadnp.random.seed(0)def read_video_pyav(container, indices):'''通过PyAV库解码视频中的特定帧。Decode the video with PyAV decoder.Args:container (`av.container.input.InputContainer`): PyAV container.indices (`List[int]`): List of frame indices to decode.Returns:result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).'''frames = []container.seek(0)start_index = indices[0]end_index = indices[-1]for i, frame in enumerate(container.decode(video=0)):if i > end_index:breakif i >= start_index and i in indices:frames.append(frame)return np.stack([x.to_ndarray(format="rgb24") for x in frames])def sample_frame_indices(clip_len, frame_sample_rate, seg_len):'''从视频中按照特定规则采样帧的索引.Sample a given number of frame indices from the video.Args:clip_len (`int`): Total number of frames to sample.frame_sample_rate (`int`): Sample every n-th frame.seg_len (`int`): Maximum allowed index of sample's last frame.Returns:indices (`List[int]`): List of sampled frame indices'''converted_len = int(clip_len * frame_sample_rate)end_idx = np.random.randint(converted_len, seg_len)start_idx = end_idx - converted_lenindices = np.linspace(start_idx, end_idx, num=clip_len)indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)return indices# video clip consists of 300 frames (10 seconds at 30 FPS)
file_path = "./transformers_basketball.avi"
"""
file_path = hf_hub_download(repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
)
"""
container = av.open(file_path)# sample 16 frames
indices = sample_frame_indices(clip_len=16, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
video = read_video_pyav(container, indices)image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
#model = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")inputs = image_processor(list(video), return_tensors="pt")with torch.no_grad():outputs = model(**inputs)logits = outputs.logits# model predicts one of the 400 Kinetics-400 classes
predicted_label = logits.argmax(-1).item()
print(model.config.id2label[predicted_label])

执行后,自动下载模型文件,构建索引,拆帧,视频分类预测:​ 

2.5 模型排名

在huggingface上,我们将视频分类(video-classification)模型按下载量从高到低排序,排在前10的模型主要由微软的xclip、南京大学的videomae、facebook的timesformer、google的vivit等四类模型构成。

三、总结

本文对transformers之pipeline的视频分类(video-classification)从概述、技术原理、pipeline参数、pipeline实战、模型排名等方面进行介绍,读者可以基于pipeline使用代码极简的代码部署计算机视觉中的视频分类(video-classification)模型,应用于视频判别场景。

期待您的3连+关注,如何还有时间,欢迎阅读我的其他文章:

《Transformers-Pipeline概述》

【人工智能】Transformers之Pipeline(概述):30w+大模型极简应用

《Transformers-Pipeline 第一章:音频(Audio)篇》

【人工智能】Transformers之Pipeline(一):音频分类(audio-classification)

【人工智能】Transformers之Pipeline(二):自动语音识别(automatic-speech-recognition)

【人工智能】Transformers之Pipeline(三):文本转音频(text-to-audio/text-to-speech)

【人工智能】Transformers之Pipeline(四):零样本音频分类(zero-shot-audio-classification)

《Transformers-Pipeline 第二章:计算机视觉(CV)篇》

【人工智能】Transformers之Pipeline(五):深度估计(depth-estimation)

【人工智能】Transformers之Pipeline(六):图像分类(image-classification)

【人工智能】Transformers之Pipeline(七):图像分割(image-segmentation)

【人工智能】Transformers之Pipeline(八):图生图(image-to-image)

【人工智能】Transformers之Pipeline(九):物体检测(object-detection)

【人工智能】Transformers之Pipeline(十):视频分类(video-classification)

【人工智能】Transformers之Pipeline(十一):零样本图片分类(zero-shot-image-classification)

【人工智能】Transformers之Pipeline(十二):零样本物体检测(zero-shot-object-detection)

《Transformers-Pipeline 第三章:自然语言处理(NLP)篇》

【人工智能】Transformers之Pipeline(十三):填充蒙版(fill-mask)

【人工智能】Transformers之Pipeline(十四):问答(question-answering)

【人工智能】Transformers之Pipeline(十五):总结(summarization)

【人工智能】Transformers之Pipeline(十六):表格问答(table-question-answering)

【人工智能】Transformers之Pipeline(十七):文本分类(text-classification)

【人工智能】Transformers之Pipeline(十八):文本生成(text-generation)

【人工智能】Transformers之Pipeline(十九):文生文(text2text-generation)

【人工智能】Transformers之Pipeline(二十):令牌分类(token-classification)

【人工智能】Transformers之Pipeline(二十一):翻译(translation)

【人工智能】Transformers之Pipeline(二十二):零样本文本分类(zero-shot-classification)

《Transformers-Pipeline 第四章:多模态(Multimodal)篇》

【人工智能】Transformers之Pipeline(二十三):文档问答(document-question-answering)

【人工智能】Transformers之Pipeline(二十四):特征抽取(feature-extraction)

【人工智能】Transformers之Pipeline(二十五):图片特征抽取(image-feature-extraction)

【人工智能】Transformers之Pipeline(二十六):图片转文本(image-to-text)

【人工智能】Transformers之Pipeline(二十七):掩码生成(mask-generation)

【人工智能】Transformers之Pipeline(二十八):视觉问答(visual-question-answering)

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • C语言常用的数据结构
  • Python | Leetcode Python题解之第331题验证二叉树的前序序列化
  • PPPoE基础笔记
  • String 事务
  • 大模型面试系列-大模型算法工程师的面试题目与解答技巧详细说明
  • 安美数字酒店宽带运营系统 weather.php 任意文件读取漏洞复现
  • redis面试(十五)公平锁队列重排
  • 封装clickHouse线程池与ibeetl解析SQL并对结果转进行转化
  • 监控电脑屏幕被拍照的原理是什么?如此有趣的电脑防偷窥知识,你一学就会!
  • MAC 终端上传文件到云服务器
  • 【银河麒麟高级服务器操作系统】libtirpc-devel 安装问题分析
  • 英国与日本经济数据影响市场走势
  • allegro PCB设计心得笔记(四) -- 显示坐标原点和更改默认产品选项
  • 计算机网络——运输层(进程之间的通信、运输层端口,UDP与TCP、TCP详解)
  • Qt实现中英文切换中QMessageBox中的中文信息怎么处理
  • [分享]iOS开发-关于在xcode中引用文件夹右边出现问号的解决办法
  • 【跃迁之路】【735天】程序员高效学习方法论探索系列(实验阶段492-2019.2.25)...
  • 11111111
  • js操作时间(持续更新)
  • js如何打印object对象
  • JS题目及答案整理
  • Mocha测试初探
  • passportjs 源码分析
  • vue学习系列(二)vue-cli
  • webpack4 一点通
  • webpack入门学习手记(二)
  • XML已死 ?
  • 百度地图API标注+时间轴组件
  • 诡异!React stopPropagation失灵
  • 后端_MYSQL
  • 日剧·日综资源集合(建议收藏)
  • 什么是Javascript函数节流?
  • 小程序button引导用户授权
  • 应用生命周期终极 DevOps 工具包
  • 正则表达式小结
  • 智能合约开发环境搭建及Hello World合约
  • ​草莓熊python turtle绘图代码(玫瑰花版)附源代码
  • (10)Linux冯诺依曼结构操作系统的再次理解
  • (11)MSP430F5529 定时器B
  • (2)nginx 安装、启停
  • (done) ROC曲线 和 AUC值 分别是什么?
  • (Matalb时序预测)PSO-BP粒子群算法优化BP神经网络的多维时序回归预测
  • (zz)子曾经曰过:先有司,赦小过,举贤才
  • (附源码)spring boot建达集团公司平台 毕业设计 141538
  • (一) springboot详细介绍
  • (一)【Jmeter】JDK及Jmeter的安装部署及简单配置
  • (转)Android学习笔记 --- android任务栈和启动模式
  • (转)IOS中获取各种文件的目录路径的方法
  • .NET 自定义中间件 判断是否存在 AllowAnonymousAttribute 特性 来判断是否需要身份验证
  • .NET6使用MiniExcel根据数据源横向导出头部标题及数据
  • .NETCORE 开发登录接口MFA谷歌多因子身份验证
  • .Net实现SCrypt Hash加密
  • .NET文档生成工具ADB使用图文教程
  • .NET业务框架的构建
  • @zabbix数据库历史与趋势数据占用优化(mysql存储查询)