Transformers 文档
TimeSformer
并获取增强的文档体验
开始使用
TimeSformer
概述
TimeSformer 模型由 Facebook Research 在 TimeSformer: Is Space-Time Attention All You Need for Video Understanding? 中提出。这项工作是动作识别领域的里程碑,是首个视频 Transformer。它启发了许多基于 Transformer 的视频理解和分类论文。
论文摘要如下
我们提出了一种无卷积的视频分类方法,该方法完全建立在空间和时间上的自注意力机制之上。我们的方法名为“TimeSformer”,通过直接从帧级别补丁序列中实现时空特征学习,将标准 Transformer 架构应用于视频。我们的实验研究比较了不同的自注意力方案,并表明“划分注意力”,即在每个块内分别应用时间注意力和空间注意力,在所考虑的设计选择中实现了最佳的视频分类准确率。尽管设计上进行了彻底的创新,但 TimeSformer 在多个动作识别基准测试中取得了最先进的结果,包括在 Kinetics-400 和 Kinetics-600 上报告的最佳准确率。最后,与 3D 卷积网络相比,我们的模型训练速度更快,可以实现显著更高的测试效率(准确率略有下降),并且还可以应用于更长的视频片段(超过一分钟)。代码和模型可在以下网址获取:this https URL。
使用技巧
有许多预训练变体。根据预训练模型所训练的数据集选择您的预训练模型。此外,每个剪辑的输入帧数会根据模型大小而变化,因此您在选择预训练模型时应考虑此参数。
资源
TimesformerConfig
类 transformers.TimesformerConfig
< 源码 >( image_size = 224 patch_size = 16 num_channels = 3 num_frames = 8 hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-06 qkv_bias = True attention_type = 'divided_space_time' drop_path_rate = 0 **kwargs )
参数
- image_size (
int
, 可选, 默认为 224) — 每个图像的大小(分辨率)。 - patch_size (
int
, 可选, 默认为 16) — 每个补丁的大小(分辨率)。 - num_channels (
int
, 可选, 默认为 3) — 输入通道的数量。 - num_frames (
int
, 可选, 默认为 8) — 每个视频中的帧数。 - hidden_size (
int
, 可选, 默认为 768) — 编码器层和池化器层的维度。 - num_hidden_layers (
int
, 可选, 默认为 12) — Transformer 编码器中隐藏层的数量。 - num_attention_heads (
int
, 可选, 默认为 12) — Transformer 编码器中每个注意力层的注意力头的数量。 - intermediate_size (
int
, 可选, 默认为 3072) — Transformer 编码器中“中间”(即,前馈)层的维度。 - hidden_act (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, 可选, 默认为 0.0) — 嵌入、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, 可选, 默认为 1e-06) — 层归一化层使用的 epsilon 值。 - qkv_bias (
bool
, 可选, 默认为True
) — 是否向 queries、keys 和 values 添加偏置。 - attention_type (
str
, 可选, 默认为"divided_space_time"
) — 要使用的注意力类型。必须是"divided_space_time"
、"space_only"
、"joint_space_time"
之一。 - drop_path_rate (
float
, 可选, 默认为 0) — 随机深度 dropout 比率。
这是用于存储 TimesformerModel 配置的配置类。它用于根据指定的参数实例化 TimeSformer 模型,定义模型架构。使用默认值实例化配置将产生与 TimeSformer facebook/timesformer-base-finetuned-k600 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import TimesformerConfig, TimesformerModel
>>> # Initializing a TimeSformer timesformer-base style configuration
>>> configuration = TimesformerConfig()
>>> # Initializing a model from the configuration
>>> model = TimesformerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
TimesformerModel
类 transformers.TimesformerModel
< 源码 >( config )
参数
- config (TimesformerConfig) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,而只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸 TimeSformer 模型 Transformer 输出原始隐藏状态,顶部没有任何特定的 head。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
前向传播
< source >( pixel_values: FloatTensor output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutput or tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_frames, num_channels, height, width)
的torch.FloatTensor
) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 VideoMAEImageProcessor.preprocess()。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
Returns
transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
transformers.modeling_outputs.BaseModelOutput 或 torch.FloatTensor
的元组 (如果传递 return_dict=False
或当 config.return_dict=False
时),包含取决于配置 (TimesformerConfig) 和输入的各种元素。
-
last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
) — 模型最后一层的输出处的隐藏状态序列。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组 (如果模型具有嵌入层,则为嵌入的输出 + 每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出的隐藏状态,加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
TimesformerModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应该在此之后调用 Module
实例,而不是调用此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
Examples
>>> import av
>>> import numpy as np
>>> from transformers import AutoImageProcessor, TimesformerModel
>>> from huggingface_hub import hf_hub_download
>>> np.random.seed(0)
>>> def read_video_pyav(container, indices):
... '''
... 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:
... break
... if 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_len
... indices = 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 = hf_hub_download(
... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)
>>> # sample 8 frames
>>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)
>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
>>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400")
>>> # prepare video for the model
>>> inputs = image_processor(list(video), return_tensors="pt")
>>> # forward pass
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 1569, 768]
TimesformerForVideoClassification
class transformers.TimesformerForVideoClassification
< source >( config )
参数
- config (TimesformerConfig) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
TimeSformer 模型转换器,顶部带有视频分类头([CLS] 标记的最终隐藏状态顶部的线性层),例如用于 ImageNet。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。
前向传播
< source >( pixel_values: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.ImageClassifierOutput or tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_frames, num_channels, height, width)
的torch.FloatTensor
) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 VideoMAEImageProcessor.preprocess()。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - labels (形状为
(batch_size,)
的torch.LongTensor
, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
中。如果config.num_labels == 1
,则计算回归损失(均方损失)。如果config.num_labels > 1
,则计算分类损失(交叉熵)。
Returns
transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
transformers.modeling_outputs.ImageClassifierOutput 或 torch.FloatTensor
的元组 (如果传递 return_dict=False
或当 config.return_dict=False
时),包含取决于配置 (TimesformerConfig) 和输入的各种元素。
-
loss (形状为
(1,)
的torch.FloatTensor
, 可选, 当提供labels
时返回) — 分类(或回归,如果 config.num_labels==1)损失。 -
logits (形状为
(batch_size, config.num_labels)
的torch.FloatTensor
) — 分类(或回归,如果 config.num_labels==1)分数(在 SoftMax 之前)。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组 (如果模型具有嵌入层,则为嵌入的输出 + 每个阶段输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每个阶段输出的隐藏状态(也称为特征图)。 -
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_heads, patch_size, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
TimesformerForVideoClassification forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应该在此之后调用 Module
实例,而不是调用此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
Examples
>>> import av
>>> import torch
>>> import numpy as np
>>> from transformers import AutoImageProcessor, TimesformerForVideoClassification
>>> from huggingface_hub import hf_hub_download
>>> np.random.seed(0)
>>> def read_video_pyav(container, indices):
... '''
... 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:
... break
... if 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_len
... indices = 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 = hf_hub_download(
... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)
>>> # sample 8 frames
>>> indices = sample_frame_indices(clip_len=8, 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 = 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])
eating spaghetti