Transformers documentation
TimeSformer
이 모델은 2021-02-09에 HF papers에 게시되었으며, 2022-12-02에 Hugging Face Transformers에 기여되었습니다.
TimeSformer
개요
The TimeSformer model was proposed in TimeSformer: Is Space-Time Attention All You Need for Video Understanding? 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.
해당 논문의 초록은 다음과 같습니다:
공간과 시간에 대한 self-attention만을 기반으로 하는 convolution-free 비디오 분류 접근법을 제시합니다. “TimeSformer”로 명명된 우리의 방법은 프레임 단위 패치 시퀀스에서 직접 시공간 특징을 학습할 수 있도록 표준 Transformer 아키텍처를 비디오에 맞게 적용합니다. 실험 연구에서는 다양한 self-attention 스킴을 비교했으며, 각 블록 내에서 시간 attention과 공간 attention을 별도로 적용하는 “divided attention”이 고려된 설계 선택지 중 가장 높은 비디오 분류 정확도를 달성하는 것으로 나타났습니다. 근본적으로 새로운 설계임에도 불구하고, TimeSformer은 Kinetics-400과 Kinetics-600을 포함한 여러 액션 인식 벤치마크에서 최첨단 결과를 달성했으며, Kinetics-400과 Kinetics-600에서 보고된 최고 정확도를 기록했습니다. 마지막으로, 3D convolutional network와 비교할 때, 우리의 모델은 학습 속도가 빠르고, 정확도가 약간 떨어지더라도 테스트 효율성을 극적으로 높일 수 있으며, 훨씬 더 긴 비디오 클립(1분 이상)에도 적용할 수 있습니다. 코드와 모델은 이 https URL에서 사용할 수 있습니다.
이 모델은 fcakyon이(가) 기여했습니다. 원본 코드는 여기에서 찾을 수 있습니다.
사용 팁
다양한 사전 학습된 변형이 있습니다. 학습에 사용된 데이터셋에 따라 사전 학습 모델을 선택하세요. 또한, 모델 크기에 따라 클립당 입력 프레임 수가 달라지므로 사전 학습 모델을 선택할 때 이 매개변수를 고려해야 합니다.
리소스
TimesformerConfig
class transformers.TimesformerConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneimage_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 16num_channels: int = 3num_frames: int = 8hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06qkv_bias: bool = Trueattention_type: str = 'divided_space_time'drop_path_rate: int = 0 )
매개변수
- 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, 선택 사항, 기본값 8) — 각 비디오의 프레임 수입니다. - hidden_size (
int, 선택 사항, 기본값768) — 숨겨진 표현의 차원입니다. - num_hidden_layers (
int, 선택 사항, 기본값12) — Transformer 디코더의 숨겨진 레이어 수. - num_attention_heads (
int, 선택 사항, 기본값12) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다. - intermediate_size (
int, 선택 사항, 기본값3072) — MLP 표현의 차원입니다. - hidden_act (
str, 선택 사항, 기본값gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어,"gelu","relu","silu"등이 있습니다. - hidden_dropout_prob (
Union[float, int], 선택 사항, 기본값0.0) — 임베딩, 인코더, 풀러의 모든 완전 연결 계층에 적용되는 드롭아웃 확률입니다. - attention_probs_dropout_prob (
Union[float, int], 선택 사항, 기본값0.0) — Attention 확률에 적용할 dropout 비율입니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다. - layer_norm_eps (
float, 선택 사항, 기본값1e-06) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다. - qkv_bias (
bool, 선택 사항, 기본값True) — 쿼리, 키, 값에 bias를 추가할지 여부. - attention_type (
str, 선택 사항, 기본값"divided_space_time") — 사용할 attention type입니다."divided_space_time","space_only","joint_space_time"중 하나여야 합니다. - drop_path_rate (
int, 선택 사항, 기본값0) — 패치 퓨전에 사용할 드롭 패스 비율입니다.
이것은 TimesformerModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Timesformer 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 facebook/timesformer-base-finetuned-k600와 유사한 구성이 생성됩니다.
Configuration 객체는 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.configTimesformerVideoProcessor
class transformers.TimesformerVideoProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.VideosKwargs'> )
매개변수
- do_convert_rgb (
bool, kwargs, 선택 사항, 기본값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, 선택 사항, 기본값False) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, 기본값2) — 이미지 크기를 조정할 때 사용할 리샘플링 필터입니다.PILImageResamplingenum 중 하나를 사용할 수 있습니다.do_resize가True로 설정된 경우에만 효과가 있습니다. - do_rescale (
bool, kwargs, 선택, 기본값True) — 이미지를 다시 스케일링할지 여부. - rescale_factor (
float, kwargs, 선택 사항, 기본값0.00392156862745098) —do_rescale이True로 설정된 경우 이미지를 재조정(rescale)하는 데 사용할 재조정 계수입니다. - do_normalize (
bool, kwargs, 선택, 기본값True) — 이미지를 정규화할지 여부. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값[0.485, 0.456, 0.406]) — 정규화에 사용할 이미지 평균입니다.do_normalize가True로 설정된 경우에만 효과가 있습니다. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값[0.229, 0.224, 0.225]) — 정규화에 사용할 이미지 표준 편차입니다.do_normalize가True로 설정된 경우에만 효과가 있습니다. - do_center_crop (
bool, kwargs, 선택, 기본값True) — 이미지를 중앙으로 크롭할지 여부. - do_pad (
bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다. - 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, 선택 사항) —ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다. - 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, 선택 사항, 기본값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인 경우 초당 샘플링할 대상 프레임 수. - 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': PyTorchtorch.Tensor객체를 반환합니다.'np': NumPynp.ndarray객체를 반환합니다.
- **kwargs (VideosKwargs, optional) — 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인자의 전체 목록은 TypedDict 클래스를 참조하세요.
TimesformerVideoProcessor 비디오 프로세서를 생성합니다.
preprocess
< source >( 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'> ) → ~image_processing_base.BatchFeature
매개변수
- 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 범위로 이루어진 단일 비디오 또는 비디오 배치(batch)를 기대합니다. 픽셀 값이 0에서 1 범위로 이루어진 비디오를 전달하는 경우do_rescale=False로 설정하십시오. - do_convert_rgb (
bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다. - do_resize (
bool, kwargs, 선택) — 이미지를 리사이즈할지 여부. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 모델의 최대 입력 차원을 설명합니다. - default_to_square (
bool, kwargs, 선택 사항) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는PILImageResamplingenum 중 하나일 수 있습니다.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, 선택) — 정규화에 사용할 이미지 평균입니다.do_normalize가True로 설정된 경우에만 효과가 있습니다. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 표준 편차.do_normalize가True로 설정된 경우에만 효과가 있습니다. - do_center_crop (
bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부. - do_pad (
bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) —center_crop을 적용한 후 출력 이미지의 크기. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) —ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다. - 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, 선택) — 처리 전에 비디오에서 프레임을 샘플링할지, 아니면 비디오 전체를 처리할지 여부를 지정합니다. - 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인 경우 초당 샘플링할 대상 프레임 수. - 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_type를 지정할 수 있습니다.
TimesformerModel
클래스 transformers.TimesformerModel
< source >( config: TimesformerConfig )
매개변수
- config (TimesformerConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
특정 헤드가 위에 없는 맨 상태의 Timesformer 모델로, 원시 hidden-states를 출력합니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( pixel_values: Tensoroutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutput or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 VideoMAEImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 VideoMAEImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 VideoMAEImageProcessor를 사용합니다). - output_attentions (
bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의attentions항목을 참조하세요. - output_hidden_states (
bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중hidden_states항목을 참고하세요. - return_dict (
bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.
반환값
BaseModelOutput 또는 tuple(torch.Tensor)
torch.Tensor의 튜플 또는 BaseModelOutput (return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(TimesformerConfig)과 입력에 따라 다양한 요소를 포함합니다.
TimesformerModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
last_hidden_state (
torch.Tensor, shape(batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple(torch.Tensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
예:
>>> 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: TimesformerConfig )
매개변수
- config (TimesformerConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
TimeSformer Model 토큰의 최종 hidden state 위에 linear layer를 올려놓은 video classification head를 갖춘 transformer 모델입니다. 예: ImageNet.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → ImageClassifierOutput or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 VideoMAEImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 VideoMAEImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 VideoMAEImageProcessor를 사용합니다). - labels (
torch.LongTensor, shape(batch_size,), 선택 사항) — 이미지 분류/회귀 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., config.num_labels - 1]범위에 있어야 합니다.config.num_labels == 1인 경우 회귀 손실(평균 제곱 오차)이 계산되고,config.num_labels > 1인 경우 분류 손실(교차 엔트로피)이 계산됩니다. - output_attentions (
bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의attentions항목을 참조하세요. - output_hidden_states (
bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중hidden_states항목을 참고하세요. - return_dict (
bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.
반환값
ImageClassifierOutput 또는 tuple(torch.Tensor)
torch.Tensor의 튜플 또는 ImageClassifierOutput입니다. return_dict=False가 전달되거나 config.return_dict=False인 경우, 구성(TimesformerConfig)과 입력에 따라 다양한 요소를 포함합니다.
TimesformerForVideoClassification의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
loss (
torch.Tensor, shape(1,), 선택 사항,labels이 제공될 때 반환됨) — 분류 (또는 config.num_labels==1인 경우 회귀) 손실.logits (
torch.Tensor, shape(batch_size, config.num_labels)) — SoftMax 적용 전 분류(또는 config.num_labels==1인 경우 회귀) 점수.hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩의 출력에 대한 것 1개 + 각 단계의 출력에 대한 것 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다. 각 단계의 출력에서 모델의 히든 스테이트(피처 맵이라고도 함).attentions (
tuple(torch.Tensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, patch_size, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
예:
>>> 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