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