Hub documentation

Hugging Face에서 timm 사용

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Hugging Face에서 timm 사용

timm, pytorch-image-models로도 알려진 이 라이브러리는 최첨단 PyTorch 이미지 모델, 사전 학습된 가중치, 그리고 학습, 추론, 검증용 유틸리티 스크립트로 구성된 오픈소스 컬렉션입니다.

이 문서는 timm 라이브러리 자체보다는 Hugging Face Hub의 timm 기능에 초점을 맞춥니다. timm 라이브러리에 대한 자세한 정보는 해당 문서를 참고하세요.

timm 모델은 모델 페이지 왼쪽의 필터를 사용하여 Hub에서 여러 개를 찾을 수 있습니다.

Hub의 모든 모델에는 몇 가지 유용한 기능이 포함되어 있습니다:

  1. 모델 작성자가 모델에 대한 정보를 추가할 수 있도록 자동으로 생성된 모델 카드
  2. Metadata 태그는 사용자가 관련 timm 모델을 발견하는 데 도움을 줍니다.
  3. 모델을 브라우저에서 직접 실험해 볼 수 있는 인터랙티브 위젯입니다.
  4. 추론 요청을 수행할 수 있는 Inference Providers입니다.

Hub의 기존 모델 사용

timm이 설치되어 있다면, Hugging Face Hub의 모든 timm 모델을 한 줄의 코드로 로드할 수 있습니다! Hub에서 모델을 선택한 후, 모델 ID 앞에 hf-hub: 접두사를 붙여 timm의 create_model 메서드에 전달하면 모델을 다운로드하고 인스턴스를 생성합니다.

import timm

# Loading https://huggingface.co/timm/eca_nfnet_l0
model = timm.create_model("hf-hub:timm/eca_nfnet_l0", pretrained=True)

특정 모델을 로드하는 방법을 확인하려면 Use in timm를 클릭하면 로드할 수 있는 작동하는 스니펫이 제공됩니다!

추론

아래 스니펫은 Hub에서 로드한 timm 모델로 추론을 수행하는 방법을 보여줍니다:

import timm
import torch
from PIL import Image
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform

# Load from Hub 🔥
model = timm.create_model(
    'hf-hub:nateraw/resnet50-oxford-iiit-pet',
    pretrained=True
)

# Set model to eval mode for inference
model.eval()

# Create Transform
transform = create_transform(**resolve_data_config(model.pretrained_cfg, model=model))

# Get the labels from the model config
labels = model.pretrained_cfg['label_names']
top_k = min(len(labels), 5)

# Use your own image file here...
image = Image.open('boxer.jpg').convert('RGB')

# Process PIL image with transforms and add a batch dimension
x = transform(image).unsqueeze(0)

# Pass inputs to model forward function to get outputs
out = model(x)

# Apply softmax to get predicted probabilities for each class
probabilities = torch.nn.functional.softmax(out[0], dim=0)

# Grab the values and indices of top 5 predicted classes
values, indices = torch.topk(probabilities, top_k)

# Prepare a nice dict of top k predictions
predictions = [
    {"label": labels[i], "score": v.item()}
    for i, v in zip(indices, values)
]
print(predictions)

다음과 같은 예측 목록이 생성됩니다:

[
    {'label': 'american_pit_bull_terrier', 'score': 0.9999998807907104},
    {'label': 'staffordshire_bull_terrier', 'score': 1.0000000149011612e-07},
    {'label': 'miniature_pinscher', 'score': 1.0000000149011612e-07},
    {'label': 'chihuahua', 'score': 1.0000000149011612e-07},
    {'label': 'beagle', 'score': 1.0000000149011612e-07}
]

모델 공유

timm 모델을 Hugging Face Hub에 직접 공유할 수 있습니다. 이렇게 하면 Hugging Face Hub에 모델의 새 버전이 게시되며, 기존에 모델 저장소가 없다면 자동으로 생성됩니다.

모델을 푸시하기 전에 Hugging Face에 로그인했는지 확인하세요:

python -m pip install huggingface_hub
hf auth login

또는 Jupyter 또는 Colaboratory 노트북에서 작업하는 것을 선호하는 경우, huggingface_hub를 설치한 후 다음으로 로그인할 수 있습니다:

from huggingface_hub import notebook_login
notebook_login()

그 다음, push_to_hf_hub 메서드를 사용하여 모델을 업로드하세요:

import timm

# Build or load a model, e.g. timm's pretrained resnet18
model = timm.create_model('resnet18', pretrained=True, num_classes=4)

###########################
# [Fine tune your model...]
###########################

# Push it to the 🤗 Hub
timm.models.hub.push_to_hf_hub(
    model,
    'resnet18-random-classifier',
    model_config={'labels': ['a', 'b', 'c', 'd']}
)

# Load your model from the Hub
model_reloaded = timm.create_model(
    'hf-hub:<your-username>/resnet18-random-classifier',
    pretrained=True
)

추가 리소스

Update on GitHub