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 ライブラリに関する詳細な情報については、そのドキュメントをご覧ください。

モデルページの左側にあるフィルターを使用して、Hub上で多数のtimmモデルを見つけることができます。

Hub上のすべてのモデルには、いくつかの便利な機能が備わっています:

  1. モデル作成者がモデルに関する情報を補完できる、自動生成されたモデルカード。
  2. メタデータタグは、ユーザーが関連するtimmモデルを見つけやすくするのに役立ちます。
  3. ブラウザ上でモデルを直接操作できるインタラクティブなウィジェットです。
  4. 推論リクエストを行うことをユーザーに許可するInference Providersです。

Hubの既存モデルを使用する

Hugging Face Hub 上の timm モデルは、timm がインストールされていれば、1 行のコードで読み込むことができます。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