# TimeSformer

## 概要

The TimeSformer model was proposed in [TimeSformer: Is Space-Time Attention All You Need for Video Understanding?](https://huggingface.co/papers/2102.05095) by Facebook Research. This work is a milestone in action-recognition field being the first video transformer. It inspired many transformer based video understanding and classification papers.

論文の抄録は以下の通りです。

*空間と時間に対する自己注意のみを用いた、畳み込みを含まない動画分類手法を提案します。当手法は「TimeSformer」と名付けられ、フレーム単位のパッチのシーケンスから時空間特徴を直接学習できるようにすることで、標準的なTransformerアーキテクチャを動画に適用します。実験研究では異なる自己注意スキームを比較し、各ブロック内で時間注意と空間注意をそれぞれ独立に適用する「divided attention」が、検討された設計選択肢の中で最も高い動画分類精度をもたらすことを示唆しています。根本的に新しい設計にもかかわらず、TimeSformerはKinetics-400およびKinetics-600における報告済み最高精度を含む、複数のアクション認識ベンチマークで最先端の結果を達成しています。最後に、3D畳み込みネットワークと比較して、当モデルは学習が高速であり、（精度のわずかな低下を伴うものの）テスト効率を劇的に高めることができ、さらに1分以上の非常に長い動画クリップにも適用できます。コードとモデルは以下で入手できます: [this https URL](https://github.com/facebookresearch/TimeSformer)。*

このモデルは[fcakyon](https://huggingface.co/fcakyon)によって提供されました。元のコードは[こちら](https://github.com/facebookresearch/TimeSformer)で確認できます。

## 使用のコツ

事前学習済みバリアントは多数あります。事前学習モデルを選択する際は、そのモデルがどのデータセットで学習されたかを基準にしてください。また、モデルサイズに応じてクリップあたりの入力フレーム数が変わるため、事前学習モデルを選択する際にはこのパラメータも考慮する必要があります。

## リソース

- [動画分類タスクガイド](../tasks/video_classification)

## TimesformerConfig[[transformers.TimesformerConfig]]

#### transformers.TimesformerConfig[[transformers.TimesformerConfig]]

```python
transformers.TimesformerConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, num_frames: int = 8, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, intermediate_size: int = 3072, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, qkv_bias: bool = True, attention_type: str = 'divided_space_time', drop_path_rate: int = 0)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/configuration_timesformer.py#L24)

**パラメータ:**

image_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`224`) : 各画像のサイズ（解像度）。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`16`) : 各パッチのサイズ（解像度）。

num_channels (`int`、*任意*、デフォルトは`3`) : 入力チャネル数。

num_frames (`int`、*optional*、デフォルトは 8) : 各動画のフレーム数。

hidden_size (`int`、*任意*、デフォルトは`768`) : 隠れ表現の次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `12`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `12`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

intermediate_size (`int`、*任意*、デフォルトは `3072`) : MLP 表現の次元数。

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

hidden_dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.0`) : embeddings、encoder、pooler 内のすべての全結合層における dropout 確率。

attention_probs_dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

qkv_bias (`bool`, *任意*, デフォルトは `True`) : クエリ、キー、バリューにバイアスを追加するかどうか。

attention_type (`str`、*任意*、デフォルトは`"divided_space_time"`) : 使用するアテンションの種類。`"divided_space_time"`、`"space_only"`、`"joint_space_time"`のいずれかである必要があります。

drop_path_rate (`int`、*任意*、デフォルトは`0`) : パッチ融合のドロップパス率です。

これはTimesformerModelの設定を保存するための設定クラスです。指定された引数に基づいてTimesformerモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[facebook/timesformer-base-finetuned-k600](https://huggingface.co/facebook/timesformer-base-finetuned-k600) と同様の設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> 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
```

## TimesformerVideoProcessor[[transformers.TimesformerVideoProcessor]]

#### transformers.TimesformerVideoProcessor[[transformers.TimesformerVideoProcessor]]

```python
transformers.TimesformerVideoProcessor(**kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/video_processing_timesformer.py#L25)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は `{'shortest_edge' : 224}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*, デフォルトは `False`) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.485, 0.456, 0.406]`) : 正規化に使用する画像の平均値です。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.229, 0.224, 0.225]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_center_crop (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を中央クロップするかどうか。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は `{'height' : 224, 'width': 224}`): `center_crop` を適用した後の出力画像のサイズ。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

do_sample_frames (`bool`, *kwargs*, *optional*, デフォルトは `False`) : 処理前に動画からフレームをサンプリングするか、動画全体を処理するかを指定します。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 動画のメタデータ。総再生時間、fps、総フレーム数などの情報を含みます。動画からのフレームサンプリングやタイムスタンプの計算に使用されます。動画を処理する前に手動でデコードしようとしている場合を除き、メタデータは渡さないでください。

fps (`Annotated[int | float | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、1 秒あたりにサンプリングするターゲットフレーム数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、サンプリングするフレームの最大数。

return_metadata (`bool`, *kwargs*, *任意*、デフォルトは `False`) : ビデオメタデータを返すかどうかを指定します。ビデオメタデータは、ビデオの長さ、fps、デコードバックエンドなどの情報を含むオブジェクトです。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 設定されている場合、特定のフレームワークのテンソルを返します。許可される値は以下の通りです。 - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

- ****kwargs** ([VideosKwargs](/docs/transformers/main/ja/main_classes/processors#transformers.VideosKwargs)、*optional*) : 各モダリティ（テキスト、画像、動画、音声）の追加処理オプションです。モデル固有のパラメータは上記に記載されています。サポートされている引数の完全なリストについては、TypedDict クラスを参照してください。

TimesformerVideoProcessor ビデオプロセッサを構築します。

#### preprocess[[transformers.TimesformerVideoProcessor.preprocess]]

```python
preprocess(videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]]], **kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/video_processing_timesformer.py#L41)

**パラメータ:**

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`) : 前処理対象の動画。ピクセル値が 0 から 255 の範囲にある、単一の動画またはバッチの動画を想定しています。ピクセル値が 0 から 1 の範囲にある動画を渡す場合は、`do_rescale=False` を設定してください。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

do_sample_frames (`bool`, *kwargs*, *optional*) : 処理前に動画からフレームをサンプリングするか、動画全体を処理するかを指定します。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 動画のメタデータ。総再生時間、fps、総フレーム数などの情報を含みます。動画からのフレームサンプリングやタイムスタンプの計算に使用されます。動画を処理する前に手動でデコードしようとしている場合を除き、メタデータは渡さないでください。

fps (`Annotated[int | float | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、1 秒あたりにサンプリングするターゲットフレーム数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、サンプリングするフレームの最大数。

return_metadata (`bool`, *kwargs*, *任意*) : ビデオメタデータを返すかどうかを指定します。ビデオメタデータは、ビデオの再生時間、fps、デコードバックエンドなどの情報を含むオブジェクトです。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

## TimesformerModel[[transformers.TimesformerModel]]

#### transformers.TimesformerModel[[transformers.TimesformerModel]]

```python
transformers.TimesformerModel(config: TimesformerConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/modeling_timesformer.py#L463)

**パラメータ:**

config ([TimesformerConfig](/docs/transformers/main/ja/model_doc/timesformer#transformers.TimesformerConfig)) : モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

特定のヘッドを付加せずに生のhidden-statesを出力する、素のTimesformerモデル。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.TimesformerModel.forward]]

```python
forward(pixel_values: FloatTensor, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/modeling_timesformer.py#L479)

**パラメータ:**

pixel_values (`torch.FloatTensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [VideoMAEImageProcessor](/docs/transformers/main/ja/model_doc/videomae#transformers.VideoMAEImageProcessor) を使用して取得できます。詳細は [VideoMAEImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [VideoMAEImageProcessor](/docs/transformers/main/ja/model_doc/videomae#transformers.VideoMAEImageProcessor) を使用します）。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** [BaseModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutput) または `tuple(torch.FloatTensor)`

設定（[TimesformerConfig](/docs/transformers/main/ja/model_doc/timesformer#transformers.TimesformerConfig)）と入力に応じて、さまざまな要素で構成される [BaseModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutput) または `torch.FloatTensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。

[TimesformerModel](/docs/transformers/main/ja/model_doc/timesformer#transformers.TimesformerModel) の forward メソッドは、`__call__` という特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）で、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
>>> 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[[transformers.TimesformerForVideoClassification]]

#### transformers.TimesformerForVideoClassification[[transformers.TimesformerForVideoClassification]]

```python
transformers.TimesformerForVideoClassification(config: TimesformerConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/modeling_timesformer.py#L596)

**パラメータ:**

config ([TimesformerConfig](/docs/transformers/main/ja/model_doc/timesformer#transformers.TimesformerConfig)) : モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

TimeSformer Model [CLS]トークンの最終的な隠れ状態の上に線形層を配置した動画分類ヘッドを備えたtransformer。ImageNetなどでの使用例。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.TimesformerForVideoClassification.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/modeling_timesformer.py#L609)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [VideoMAEImageProcessor](/docs/transformers/main/ja/model_doc/videomae#transformers.VideoMAEImageProcessor) を使用して取得できます。詳細は [VideoMAEImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [VideoMAEImageProcessor](/docs/transformers/main/ja/model_doc/videomae#transformers.VideoMAEImageProcessor) を使用します）。

labels (`torch.LongTensor`、shape `(batch_size,)`、*任意*) : 画像分類/回帰の損失を計算するためのラベル。インデックスは `[0, ..., config.num_labels - 1]` の範囲である必要があります。`config.num_labels == 1` の場合は回帰損失（Mean-Square loss）が計算され、`config.num_labels > 1` の場合は分類損失（Cross-Entropy）が計算されます。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** [ImageClassifierOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput) または `tuple(torch.FloatTensor)`

設定（[TimesformerConfig](/docs/transformers/main/ja/model_doc/timesformer#transformers.TimesformerConfig)）や入力に応じて、さまざまな要素で構成される [ImageClassifierOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput)、または `torch.FloatTensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。

[TimesformerForVideoClassification](/docs/transformers/main/ja/model_doc/timesformer#transformers.TimesformerForVideoClassification)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 分類（または config.num_labels==1 の場合は回帰）の損失。
- **logits** (`torch.FloatTensor`、shape `(batch_size, config.num_labels)`) -- SoftMax 適用前の分類（または config.num_labels==1 の場合は回帰）スコア。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返される) -- `torch.FloatTensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各ステージの出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。各ステージの出力におけるモデルの隠れ状態（特徴マップとも呼ばれる）です。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, patch_size, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
>>> 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
```

