Transformers 文档
TimeSformer
并获得增强的文档体验
开始使用
TimeSformer
概述
TimeSformer 模型由 Facebook Research 在TimeSformer: 视频理解只需要时空注意力吗?中提出。这项工作是动作识别领域的里程碑,是首个视频 Transformer。它启发了许多基于 Transformer 的视频理解和分类论文。
论文摘要如下:
我们提出了一种纯粹基于空间和时间自注意力机制的无卷积视频分类方法。我们的方法名为 “TimeSformer”,通过直接从一系列帧级图像块中进行时空特征学习,将标准 Transformer 架构应用于视频。我们的实验研究比较了不同的自注意力方案,并表明在每个模块中单独应用时间注意力和空间注意力的“分段注意力”在所考虑的设计选择中能带来最佳的视频分类准确性。尽管设计理念全新,TimeSformer 在多个动作识别基准测试中取得了最先进的结果,包括在 Kinetics-400 和 Kinetics-600 上报告的最佳准确率。最后,与 3D 卷积网络相比,我们的模型训练速度更快,可以实现显著更高的测试效率(在准确性略有下降的情况下),并且还可以应用于更长的视频片段(超过一分钟)。代码和模型可在此处获取:此 https URL。
使用技巧
有许多预训练的变体。根据训练数据集选择您的预训练模型。此外,每个片段的输入帧数会根据模型大小而变化,因此在选择预训练模型时应考虑此参数。
资源
TimesformerConfig
class 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) — 随机深度 (stochastic depth) 的 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
class transformers.TimesformerModel
< 源 >( config )
参数
- config (TimesformerModel) — 模型的配置类,包含模型的所有参数。使用配置文件初始化并不会加载与模型相关的权重,只加载配置。请查阅 from_pretrained() 方法以加载模型权重。
裸 Timesformer 模型,输出原始隐藏状态,顶部没有任何特定头部。
此模型继承自 PreTrainedModel。请查阅超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 的子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档以了解所有与一般用法和行为相关的事项。
forward
< 源 >( 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 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
形状为(batch_size, num_channels, image_size, image_size)
) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而非普通元组。
返回
transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutput 或一个 torch.FloatTensor
元组(如果传入 return_dict=False
或 config.return_dict=False
),包含根据配置(TimesformerConfig)和输入而定的各种元素。
-
last_hidden_state (
torch.FloatTensor
, 形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 -
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 的前向传播方法,覆盖了 __call__
特殊方法。
尽管前向传播的配方需要在该函数中定义,但在此之后应该调用 Module
实例,而不是直接调用此函数,因为前者会处理预处理和后处理步骤,而后者会默默忽略它们。
示例
>>> 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
< 源 >( config )
参数
- config (TimesformerForVideoClassification) — 模型的配置类,包含模型的所有参数。使用配置文件初始化并不会加载与模型相关的权重,只加载配置。请查阅 from_pretrained() 方法以加载模型权重。
TimeSformer 模型 Transformer,顶部带有视频分类头([CLS] 标记最终隐藏状态顶部的线性层),例如用于 ImageNet。
此模型继承自 PreTrainedModel。请查阅超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 的子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档以了解所有与一般用法和行为相关的事项。
forward
< 源 >( 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 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor
形状为(batch_size, num_channels, image_size, image_size)
, 可选) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - labels (
torch.LongTensor
形状为(batch_size,)
, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。如果config.num_labels == 1
,则计算回归损失(均方损失);如果config.num_labels > 1
,则计算分类损失(交叉熵)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而非普通元组。
返回
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 的前向传播方法,覆盖了 __call__
特殊方法。
尽管前向传播的配方需要在该函数中定义,但在此之后应该调用 Module
实例,而不是直接调用此函数,因为前者会处理预处理和后处理步骤,而后者会默默忽略它们。
示例
>>> 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