Transformers documentation
HGNet-V2
이 모델은 2025-04-29에 Hugging Face Transformers에 기여되었습니다.
HGNet-V2
HGNetV2는 NVIDIA GPU에서 최적의 정확도-지연 시간 트레이드오프를 위해 설계된 차세대 합성곱 신경망(CNN) 백본입니다. 기존 HGNet을 기반으로 한 HGNetV2는 빠른 추론 속도로 높은 정확도를 제공하며, 이미지 분류, 객체 감지, 분할과 같은 작업에서 뛰어난 성능을 발휘하여 GPU 기반 컴퓨터 비전 애플리케이션에 실용적인 선택지가 됩니다.
모든 원본 HGNet V2 모델은 USTC 조직에서 찾을 수 있습니다.
이 모델은 VladOS95-cyber님이 기여했습니다. 다양한 컴퓨터 비전 작업에 HGNet V2를 적용하는 방법에 대한 추가 예제는 오른쪽 사이드바의 HGNet V2 모델들을 클릭하여 확인하세요.
아래 예제는 Pipeline 또는 AutoModel 클래스를 사용하여 이미지를 분류하는 방법을 보여줍니다.
from transformers import pipeline
pipeline = pipeline(
task="image-classification",
model="ustc-community/hgnet-v2",
device=0
)
pipeline("http://images.cocodataset.org/val2017/000000039769.jpg")import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, HGNetV2ForImageClassification
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
model = HGNetV2ForImageClassification.from_pretrained("ustc-community/hgnet-v2", device_map="auto")
processor = AutoImageProcessor.from_pretrained("ustc-community/hgnet-v2")
inputs = processor(images=image, return_tensors="pt").to(model.device)
with torch.no_grad():
logits = model(**inputs).logits
predicted_class_id = logits.argmax(dim=-1).item()
class_labels = model.config.id2label
predicted_class_label = class_labels[predicted_class_id]
print(f"The predicted class label is: {predicted_class_label}")HGNetV2Config
클래스 transformers.HGNetV2Config
< 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 = Nonenum_channels: int = 3embedding_size: int = 64depths: list[int] | tuple[int, ...] = (3, 4, 6, 3)hidden_sizes: list[int] | tuple[int, ...] = (256, 512, 1024, 2048)hidden_act: str = 'relu'_out_features: list[str] | None = None_out_indices: list[int] | None = Nonestem_channels: list[int] | tuple[int, ...] = (3, 32, 48)stem_strides: Sequence = (2, 1, 1, 2, 1)stage_in_channels: list[int] | tuple[int, ...] = (48, 128, 512, 1024)stage_mid_channels: list[int] | tuple[int, ...] = (48, 96, 192, 384)stage_out_channels: list[int] | tuple[int, ...] = (128, 512, 1024, 2048)stage_num_blocks: list[int] | tuple[int, ...] = (1, 1, 3, 1)stage_downsample: list[bool] | tuple[bool, ...] = (False, True, True, True)stage_downsample_strides: Sequence = (2, 2, 2, 2)stage_light_block: list[bool] | tuple[bool, ...] = (False, False, True, True)stage_kernel_size: list[int] | tuple[int, ...] = (3, 3, 5, 5)stage_numb_of_layers: list[int] | tuple[int, ...] = (6, 6, 6, 6)use_learnable_affine_block: bool = Falseinitializer_range: float = 0.02 )
매개변수
- num_channels (
int, 선택 사항, 기본값3) — 입력 채널의 수입니다. - embedding_size (
int, 선택 사항, 기본값64) — 임베딩 및 숨겨진 상태의 차원. - depths (
Union[list[int], tuple[int, ...]], 선택 사항, 기본값(3, 4, 6, 3)) — Transformer의 각 레이어 깊이. - hidden_sizes (
Union[list[int], tuple[int, ...]], 선택 사항, 기본값(256, 512, 1024, 2048)) — 모델의 각 단계에서의 차원(숨김 크기). - hidden_act (
str, 선택 사항, 기본값relu) — 디코더의 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어,"gelu","relu","silu"등이 있습니다. - stem_channels (
list[int], 선택 사항, 기본값은[3, 32, 48]) — stem 레이어의 채널 차원:- 첫 번째 숫자(3)는 입력 이미지의 채널 수입니다
- 두 번째 숫자(32)는 중간 stem 채널 수입니다
- 세 번째 숫자(48)는 출력 stem 채널 수입니다
- stem_strides (
Sequence[int | list[int] | tuple[int, ...]], 선택 사항, 기본값(2, 1, 1, 2, 1)) — stem 레이어의 스트라이드 패턴입니다. - stage_in_channels (
list[int], 선택 사항, 기본값[48, 128, 512, 1024]) — backbone의 각 stage에 대한 입력 채널 차원입니다. 각 stage의 입력이 가질 채널 수를 정의합니다. - stage_mid_channels (
list[int], 선택 사항, 기본값[48, 96, 192, 384]) — backbone의 각 stage에 대한 중간 채널 차원입니다. 각 stage의 중간 레이어에서 사용되는 채널 수를 정의합니다. - stage_out_channels (
list[int], 선택 사항, 기본값[128, 512, 1024, 2048]) — backbone의 각 stage에 대한 출력 채널 차원입니다. 각 stage의 출력이 가질 채널 수를 정의합니다. - stage_num_blocks (
list[int], 선택 사항, 기본값[1, 1, 3, 1]) — backbone의 각 stage에서 사용할 블록의 수입니다. 이 값은 컨볼루션 블록을 얼마나 쌓을지를 지정하여 각 stage의 깊이를 제어합니다. - stage_downsample (
list[bool], 선택 사항, 기본값[False, True, True, True]) — 각 단계에서 feature map을 다운샘플링할지 여부를 나타냅니다.True인 경우, feature map의 공간 차원이 축소됩니다. - stage_downsample_strides (
Sequence[int | list[int] | tuple[int, ...]], 선택 사항, 기본값(2, 2, 2, 2)) — 각 stage layer의 stride 패턴입니다. - stage_light_block (
list[bool], 선택 사항, 기본값[False, False, True, True]) — 각 stage에서 light block을 사용할지 여부를 나타냅니다. Light block은 매개변수가 더 적을 수 있는 convolutional block의 변형입니다. - stage_kernel_size (
list[int], 선택 사항, 기본값[3, 3, 5, 5]) — 각 단계의 합성곱 계층에 사용할 커널 크기입니다. - stage_numb_of_layers (
list[int], 선택 사항, 기본값[6, 6, 6, 6]) — 각 stage 블록에 사용할 레이어 수입니다. - use_learnable_affine_block (
bool, 선택 사항, 기본값False) — 네트워크에서 Learnable Affine Blocks(LAB)를 사용할지 여부입니다. LAB은 특정 연산 이후에 학습 가능한 scale 및 bias 매개변수를 추가합니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
이것은 HGNetV2Backbone의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Hgnet V2 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 ustc-community/dfine_x_coco와 유사한 설정이 생성됩니다.
Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.
HGNetV2Backbone
forward
< source >( pixel_values: Tensoroutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BackboneOutput or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은image_processor_class.__call__를 참조하세요. (processor_class는 이미지 처리에image_processor_class를 사용합니다.) - output_hidden_states (
bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중hidden_states항목을 참고하세요. - return_dict (
bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.
반환값
BackboneOutput 또는 tuple(torch.Tensor)
BackboneOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되거나 config.return_dict=False인 경우)로, HGNetV2Config 및 입력에 따라 다양한 요소를 포함합니다.
HGNetV2Backbone의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
feature_maps (
tuple(torch.Tensor), shape(batch_size, num_channels, height, width)) — 각 단계의 feature map입니다.hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) — 임베딩의 출력 하나와 각 레이어의 출력 하나씩을 포함하는torch.Tensor의 튜플로, 백본에 따라 shape가(batch_size, sequence_length, hidden_size)또는(batch_size, num_channels, height, width)입니다.각 단계의 출력에서 모델의 Hidden-states와 초기 임베딩 출력을 포함합니다.
attentions (
tuple(torch.Tensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다. 백본이 attention을 사용하는 경우에만 적용됩니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
예:
>>> from transformers import HGNetV2Config, HGNetV2Backbone
>>> import torch
>>> config = HGNetV2Config()
>>> model = HGNetV2Backbone(config)
>>> pixel_values = torch.randn(1, 3, 224, 224)
>>> with torch.no_grad():
... outputs = model(pixel_values)
>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 2048, 7, 7]HGNetV2ForImageClassification
class transformers.HGNetV2ForImageClassification
< source >( config: HGNetV2Config )
매개변수
- config (HGNetV2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
이미지 분류 헤드가 위에 있는 HGNetV2 모델(풀링된 특징 위에 선형 레이어가 있는 형태)로, 예를 들어 ImageNet에 사용됩니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → ImageClassifierOutputWithNoAttention or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은image_processor_class.__call__를 참조하세요 (processor_class는 이미지 처리에image_processor_class를 사용합니다). - labels (
torch.LongTensor, shape(batch_size,), 선택 사항) — 이미지 분류/회귀 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., config.num_labels - 1]범위에 있어야 합니다.config.num_labels == 1인 경우 회귀 손실(평균 제곱 오차)이 계산되고,config.num_labels > 1인 경우 분류 손실(교차 엔트로피)이 계산됩니다. - output_hidden_states (
bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중hidden_states항목을 참고하세요. - return_dict (
bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.
반환값
ImageClassifierOutputWithNoAttention 또는 tuple(torch.Tensor)
torch.Tensor의 튜플 또는 ImageClassifierOutputWithNoAttention (return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(HGNetV2Config)과 입력에 따라 다양한 요소를 포함합니다.
HGNetV2ForImageClassification의 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, num_channels, height, width)입니다. 각 단계의 출력에서 모델의 히든 스테이트(피처 맵이라고도 함).
예:
>>> import torch
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import HGNetV2ForImageClassification, AutoImageProcessor
>>> from PIL import Image
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> model = HGNetV2ForImageClassification.from_pretrained("ustc-community/hgnet-v2")
>>> processor = AutoImageProcessor.from_pretrained("ustc-community/hgnet-v2")
>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> outputs.logits.shape
torch.Size([1, 2])