Hub 文件

在 Hugging Face Hub 上使用 timm

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

在 Hugging Face 上使用 timm

timm,也稱為 pytorch-image-models,是一個開源的 PyTorch 影像模型集合,包含預訓練權重和用於訓練、推理和驗證的實用指令碼。

本文件重點介紹 Hugging Face Hub 中的 timm 功能,而非 timm 庫本身。有關 timm 庫的詳細資訊,請訪問其文件

您可以使用模型頁面左側的過濾器,在 Hub 上找到許多 timm 模型。

Hub 上的所有模型都具有一些有用的功能:

  1. 自動生成的模型卡片,模型作者可以使用有關其模型的資訊來完善它。
  2. 元資料標籤可幫助使用者發現相關的 timm 模型。
  3. 一個互動式小部件,您可以在瀏覽器中直接使用該模型。
  4. 一個推理 API,允許使用者發出推理請求。

使用 Hub 中的現有模型

只要安裝了 timm,就可以使用一行程式碼從 Hugging Face Hub 載入任何 timm 模型!選擇 Hub 中的模型後,將模型 ID 字首為 hf-hub: 傳遞給 timmcreate_model 方法以下載並例項化模型。

import timm

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

如果您想了解如何載入特定模型,可以單擊在 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 notebook 中工作,一旦安裝了 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
)

推理小部件和 API

Hub 上的所有 timm 模型都自動配備了推理小部件,如下所示的nateraw/timm-resnet50-beans。此外,timm 模型可以透過推理 API 訪問,您可以透過 HTTP 使用 cURL、Python 的 requests 庫或您首選的網路請求方法進行訪問。

curl https://api-inference.huggingface.co/models/nateraw/timm-resnet50-beans \
        -X POST \
        --data-binary '@beans.jpeg' \
        -H "Authorization: Bearer {$HF_API_TOKEN}"
# [{"label":"angular_leaf_spot","score":0.9845947027206421},{"label":"bean_rust","score":0.01368315052241087},{"label":"healthy","score":0.001722085871733725}]

其他資源

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.