Transformers documentation

YOLOS

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2021-06-01에 HF papers에 게시되었으며, 2022-05-02에 Hugging Face Transformers에 기여되었습니다.

FlashAttention SDPA

YOLOS

YOLOS는 최소한의 수정과 region priors를 사용하여 Vision Transformer (ViT)로 객체 감지를 수행합니다. 2D 공간 구조에 대한 지식을 활용하여, 특화된 객체 감지 모델 및 프레임워크와 동등한 성능을 달성할 수 있습니다.

모든 원본 YOLOS 체크포인트는 HUST Vision Lab 조직에서 찾을 수 있습니다.

drawing YOLOS architecture. Taken from the original paper.

이 모델은 nielsr에 의해 기여되었습니다. YOLOS를 다양한 객체 감지 작업에 적용하는 방법에 대한 추가 예제는 오른쪽 사이드바의 YOLOS 모델을 클릭하여 확인하세요.

아래 예제는 Pipeline 또는 AutoModel 클래스를 사용하여 객체를 감지하는 방법을 보여줍니다.

Pipeline
Automodel
from transformers import pipeline


detector = pipeline(
    task="object-detection",
    model="hustvl/yolos-base",
    device=0
)
detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")

The input is a single word "Notes". 참고

  • 이미지(및 선택적 target)를 모델에 맞게 준비하려면 YolosImageProcessor를 사용합니다. DETR과 달리 YOLOS는 pixel_mask가 필요하지 않습니다.

리소스

YolosConfig

클래스 transformers.YolosConfig

< >

( 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 = Nonehidden_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-12image_size: list[int] | tuple[int, ...] = (512, 864)patch_size: int | list[int] | tuple[int, int] = 16num_channels: int = 3qkv_bias: bool = Truenum_detection_tokens: int = 100use_mid_position_embeddings: bool = Trueauxiliary_loss: bool = Falseclass_cost: int = 1bbox_cost: int = 5giou_cost: int = 2bbox_loss_coefficient: int = 5giou_loss_coefficient: int = 2eos_coefficient: float = 0.1 )

매개변수

  • 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-12) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • image_size (Union[list[int], tuple[int, ...]], 선택, 기본값 (512, 864)) — 각 이미지의 크기(해상도).
  • patch_size (Union[int, list[int], tuple[int, int]], 선택 사항, 기본값 16) — 각 패치의 크기(해상도)입니다.
  • num_channels (int, 선택 사항, 기본값 3) — 입력 채널의 수입니다.
  • qkv_bias (bool, 선택 사항, 기본값 True) — 쿼리, 키, 값에 bias를 추가할지 여부.
  • num_detection_tokens (int, 선택 사항, 기본값 100) — 탐지 토큰의 개수입니다.
  • use_mid_position_embeddings (bool, 선택 사항, 기본값 True) — 중간 레이어 위치 인코딩을 사용할지 여부입니다.
  • auxiliary_loss (bool, 선택 사항, 기본값 False) — 보조 디코딩 손실(각 디코더 레이어의 손실)을 사용할지 여부입니다.
  • class_cost (int, 선택 사항, 기본값 1) — 헝가리안 매칭 비용에서 분류 오류의 상대적 가중치입니다.
  • bbox_cost (int, 선택 사항, 기본값 5) — 헝가리안 매칭 비용에서 L1 바운딩 박스 오차의 상대적 가중치입니다.
  • giou_cost (int, 선택 사항, 기본값 2) — 헝가리안 매칭 비용에서 일반화 IoU 손상의 상대적 가중치.
  • bbox_loss_coefficient (int, 선택 사항, 기본값 5) — panoptic segmentation loss에서 L1 bounding box loss의 상대적 가중치입니다.
  • giou_loss_coefficient (int, 선택 사항, 기본값 2) — panoptic segmentation loss에서 generalized IoU loss의 상대적 가중치입니다.
  • eos_coefficient (float, 선택 사항, 기본값 0.1) — 객체 감지 손실에서 ‘no-object’ 클래스의 상대 분류 가중치입니다.

이것은 YolosModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Yolos 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 hustvl/yolos-base와 유사한 설정이 생성됩니다.

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> from transformers import YolosConfig, YolosModel

>>> # Initializing a YOLOS hustvl/yolos-base style configuration
>>> configuration = YolosConfig()

>>> # Initializing a model (with random weights) from the hustvl/yolos-base style configuration
>>> model = YolosModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

YolosImageProcessor

class transformers.YolosImageProcessor

< >

( **kwargs: *<class 'transformers.models.yolos.image_processing_yolos.YolosImageProcessorKwargs'> )

매개변수

  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택 사항, 기본값 True) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, 기본값 {'shortest_edge' -- 800, 'longest_edge': 1333}): 모델에 전달되는 최대 입력 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항, 기본값 False) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, 기본값 2) — 이미지 크기를 조정할 때 사용할 리샘플링 필터입니다. PILImageResampling enum 중 하나를 사용할 수 있습니다. 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_pad (bool, kwargs, 선택, 기본값 True) — 이미지에 패딩을 적용할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • 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) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • format (str, kwargs, optional, 기본값 AnnotationFormat.COCO_DETECTION) — 주석의 데이터 형식입니다. “coco_detection” 또는 “coco_panoptic” 중 하나입니다.
  • do_convert_annotations (bool, kwargs, 선택 사항, 기본값 True) — YOLOS 모델이 기대하는 형식으로 어노테이션을 변환할지 여부를 제어합니다. 바운딩 박스를 (center_x, center_y, width, height) 형식으로 변환하고 범위를 [0, 1]로 설정합니다. preprocess 메서드의 do_convert_annotations 매개변수로 재정의할 수 있습니다.

YolosImageProcessor 이미지 프로세서를 생성합니다.

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = Nonereturn_segmentation_masks: bool | None = Nonemasks_path: str | pathlib.Path | None = None**kwargs: *<class 'transformers.models.yolos.image_processing_yolos.YolosImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

매개변수

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 전처리할 이미지. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다. 픽셀 값이 0에서 1 사이인 이미지를 전달하는 경우 do_rescale=False로 설정하세요.
  • annotations (AnnotationType 또는 list[AnnotationType], 선택) — 이미지에 적용되는 패딩에 따라 변환할 어노테이션입니다.
  • return_segmentation_masks (bool, 선택 사항, 기본값 self.return_segmentation_masks) — 분할 마스크를 반환할지 여부.
  • masks_path (str 또는 pathlib.Path, 선택) — 분할 마스크가 포함된 디렉터리의 경로입니다.
  • 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인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는 PILImageResampling enum 중 하나일 수 있습니다. 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_pad (bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • 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) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • format (str, kwargs, optional, 기본값 AnnotationFormat.COCO_DETECTION) — 주석의 데이터 형식입니다. “coco_detection” 또는 “coco_panoptic” 중 하나입니다.
  • do_convert_annotations (bool, kwargs, 선택 사항, 기본값 True) — YOLOS 모델이 기대하는 형식으로 어노테이션을 변환할지 여부를 제어합니다. 바운딩 박스를 (center_x, center_y, width, height) 형식으로 변환하고 범위를 [0, 1]로 설정합니다. preprocess 메서드의 do_convert_annotations 매개변수로 재정의할 수 있습니다.

반환값

~image_processing_base.BatchFeature

  • data (dict) — call 메서드가 반환하는 리스트/배열/텐서 딕셔너리(‘pixel_values’ 등).
  • tensor_type (Union[None, str, TensorType], 선택 사항) — 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type를 지정할 수 있습니다.

YolosImageProcessorPil

class transformers.YolosImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.yolos.image_processing_pil_yolos.YolosImageProcessorKwargs'> )

매개변수

  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택 사항, 기본값 True) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, 기본값 {'shortest_edge' -- 800, 'longest_edge': 1333}): 모델에 전달되는 최대 입력 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항, 기본값 False) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, 기본값 2) — 이미지 크기를 조정할 때 사용할 리샘플링 필터입니다. PILImageResampling enum 중 하나를 사용할 수 있습니다. 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_pad (bool, kwargs, 선택, 기본값 True) — 이미지에 패딩을 적용할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • 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) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • format (str, kwargs, optional, 기본값 AnnotationFormat.COCO_DETECTION) — 주석의 데이터 형식입니다. “coco_detection” 또는 “coco_panoptic” 중 하나입니다.
  • do_convert_annotations (bool, kwargs, 선택 사항, 기본값 True) — YOLOS 모델이 기대하는 형식으로 어노테이션을 변환할지 여부를 제어합니다. 바운딩 박스를 (center_x, center_y, width, height) 형식으로 변환하고 범위를 [0, 1]로 설정합니다. preprocess 메서드의 do_convert_annotations 매개변수로 재정의할 수 있습니다.

YolosImageProcessor 이미지 프로세서를 생성합니다.

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = Nonereturn_segmentation_masks: bool | None = Nonemasks_path: str | pathlib.Path | None = None**kwargs: *<class 'transformers.models.yolos.image_processing_pil_yolos.YolosImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

매개변수

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 전처리할 이미지. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다. 픽셀 값이 0에서 1 사이인 이미지를 전달하는 경우 do_rescale=False로 설정하세요.
  • annotations (AnnotationType 또는 list[AnnotationType], 선택) — 이미지에 적용되는 패딩에 따라 변환할 어노테이션입니다.
  • return_segmentation_masks (bool, 선택 사항, 기본값 self.return_segmentation_masks) — 분할 마스크를 반환할지 여부.
  • masks_path (str 또는 pathlib.Path, 선택) — 분할 마스크가 포함된 디렉터리의 경로입니다.
  • 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인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는 PILImageResampling enum 중 하나일 수 있습니다. 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_pad (bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • 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) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • format (str, kwargs, optional, 기본값 AnnotationFormat.COCO_DETECTION) — 주석의 데이터 형식입니다. “coco_detection” 또는 “coco_panoptic” 중 하나입니다.
  • do_convert_annotations (bool, kwargs, 선택 사항, 기본값 True) — YOLOS 모델이 기대하는 형식으로 어노테이션을 변환할지 여부를 제어합니다. 바운딩 박스를 (center_x, center_y, width, height) 형식으로 변환하고 범위를 [0, 1]로 설정합니다. preprocess 메서드의 do_convert_annotations 매개변수로 재정의할 수 있습니다.

반환값

~image_processing_base.BatchFeature

  • data (dict) — call 메서드가 반환하는 리스트/배열/텐서 딕셔너리(‘pixel_values’ 등).
  • tensor_type (Union[None, str, TensorType], 선택 사항) — 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type를 지정할 수 있습니다.

패딩

< >

( image: ndarraypadded_size: tupleannotation: dict[str, typing.Any] | None = Noneupdate_bboxes: bool = Truefill: int = 0 )

post_process_object_detection

< >

( outputsthreshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] = None ) → list[Dict]

매개변수

  • outputs (YolosObjectDetectionOutput) — 모델의 원시 출력입니다.
  • threshold (float, 선택 사항) — 객체 감지 예측을 유지하기 위한 점수 임계값.
  • target_sizes (torch.Tensor 또는 list[tuple[int, int]], 선택 사항) — (batch_size, 2) 형태의 Tensor 또는 각 이미지의 대상 크기 (height, width)를 포함하는 튜플(tuple[int, int])의 리스트입니다. 설정하지 않으면 예측 결과가 리사이즈되지 않습니다.

반환값

list[Dict]

…

YolosForObjectDetection의 원시 출력을 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 형식의 최종 바운딩 박스로 변환합니다. PyTorch만 지원합니다.

YolosModel

class transformers.YolosModel

< >

( config: YolosConfigadd_pooling_layer: bool = True )

매개변수

  • config (YolosConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
  • add_pooling_layer (bool, 선택 사항, 기본값 True) — pooling layer를 추가할지 여부

Yolos 모델은 특정 헤드가 없는 상태에서 원시 hidden-states를 출력합니다.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 YolosImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 YolosImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 YolosImageProcessor를 사용합니다).

반환값

BaseModelOutputWithPooling 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 BaseModelOutputWithPooling (return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(YolosConfig)과 입력에 따라 다양한 요소를 포함합니다.

YolosModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • pooler_output (torch.Tensor, shape (batch_size, hidden_size)) — 보조 사전 학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 후의 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전 학습 동안 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.

  • 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 가중치.

예:

YolosForObjectDetection

class transformers.YolosForObjectDetection

< >

( config: YolosConfig )

매개변수

  • config (YolosConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

YOLOS 모델(ViT 인코더로 구성)의 상단에 객체 탐지 헤드를 배치하여 COCO 탐지와 같은 작업을 수행합니다.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( pixel_values: Tensorlabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → YolosObjectDetectionOutput or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 YolosImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 YolosImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 YolosImageProcessor를 사용합니다).
  • labels (list[Dict], 길이 (batch_size,), 선택 사항) — 이분 매칭 손실을 계산하기 위한 라벨. 각 딕셔너리는 최소한 ‘class_labels’와 ‘boxes’라는 두 개의 키를 포함해야 합니다(각각 배치 내 이미지의 클래스 라벨과 바운딩 박스). 클래스 라벨 자체는 torch.LongTensor이며 길이는 (number of bounding boxes in the image,)이고, boxes는 torch.Tensor이며 모양은 (number of bounding boxes in the image, 4)입니다.

반환값

YolosObjectDetectionOutput 또는 tuple(torch.Tensor)

YolosObjectDetectionOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(YolosConfig)과 입력에 따라 다양한 요소를 포함합니다.

YolosForObjectDetection의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.Tensor, shape (1,), 선택 사항, labels가 제공될 때 반환됨) — 클래스 예측에 대한 음의 로그 가능도(교차 엔트로피)와 바운딩 박스 손실의 선형 결합으로 계산된 총 손실입니다. 후자는 L1 손실과 일반화된 스케일 불변 IoU 손실의 선형 결합으로 정의됩니다.

  • loss_dict (Dict, 선택) — 개별 손실 값을 포함하는 사전입니다. 로깅에 유용합니다.

  • logits (torch.Tensor, shape (batch_size, num_queries, num_classes + 1)) — 모든 query에 대한 분류 logits(no-object 포함).

  • pred_boxes (torch.Tensor, shape (batch_size, num_queries, 4)) — 모든 query에 대한 정규화된 박스 좌표로, (center_x, center_y, width, height)로 표현됩니다. 이 값들은 배치 내 각 개별 이미지의 크기에 대해 [0, 1] 범위로 정규화되어 있습니다(가능한 패딩은 무시). ~YolosImageProcessor.post_process를 사용하면 정규화되지 않은 바운딩 박스를 가져올 수 있습니다.

  • auxiliary_outputs (list[Dict], 선택) — 선택 사항이며, 보조 손실이 활성화된 경우(즉, config.auxiliary_loss가 True로 설정된 경우)와 라벨이 제공된 경우에만 반환됩니다. 각 디코더 레이어에 대해 위의 두 키(logits와 pred_boxes)를 포함하는 사전의 목록입니다.

  • 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 가중치.

예:

>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("hustvl/yolos-tiny")
>>> model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-tiny")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
...     0
... ]

>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
...     box = [round(i, 2) for i in box.tolist()]
...     print(
...         f"Detected {model.config.id2label[label.item()]} with confidence "
...         f"{round(score.item(), 3)} at location {box}"
...     )
Detected remote with confidence 0.991 at location [46.48, 72.78, 178.98, 119.3]
Detected remote with confidence 0.908 at location [336.48, 79.27, 368.23, 192.36]
Detected cat with confidence 0.934 at location [337.18, 18.06, 638.14, 373.09]
Detected cat with confidence 0.979 at location [10.93, 53.74, 313.41, 470.67]
Detected remote with confidence 0.974 at location [41.63, 72.23, 178.09, 119.99]
Update on GitHub