# Hugging Faceでのtimmの使用

`timm`（[pytorch-image-models](https://github.com/rwightman/pytorch-image-models)としても知られています）は、最先端の PyTorch 画像モデル、事前学習済み重み、および学習・推論・検証用のユーティリティスクリプトからなるオープンソースのコレクションです。

このドキュメントは、`timm` ライブラリ自体ではなく、Hugging Face Hub における `timm` の機能に焦点を当てています。`timm` ライブラリに関する詳細な情報については、[そのドキュメント](https://huggingface.co/docs/timm)をご覧ください。

[モデルページ](https://huggingface.co/models?library=timm&sort=downloads)の左側にあるフィルターを使用して、Hub上で多数の`timm`モデルを見つけることができます。

Hub上のすべてのモデルには、いくつかの便利な機能が備わっています:
1. モデル作成者が[モデルに関する情報](./model-cards)を補完できる、自動生成されたモデルカード。
2. メタデータタグは、ユーザーが関連する`timm`モデルを見つけやすくするのに役立ちます。
3. ブラウザ上でモデルを直接操作できる[インタラクティブなウィジェット](./models-widgets)です。
4. 推論リクエストを行うことをユーザーに許可する[Inference Providers](./models-inference)です。

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

Hugging Face Hub 上の `timm` モデルは、`timm` がインストールされていれば、1 行のコードで読み込むことができます。Hub からモデルを選択したら、モデル ID に `hf-hub:` をプレフィックスとして付与し、`timm` の `create_model` メソッドに渡すことで、モデルをダウンロードしてインスタンス化できます。

```py
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`モデルで推論を実行する方法を示しています。

```py
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)
```

これにより、次のような予測のリストが得られるはずです。

```py
[
    {'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 にログインしていることを確認してください:

```sh
python -m pip install huggingface_hub
hf auth login
```

または、JupyterやColaboratoryのノートブックで作業する方がお好みであれば、`huggingface_hub`をインストールした後、以下でログインできます:

```py
from huggingface_hub import notebook_login
notebook_login()
```

次に、`push_to_hf_hub` メソッドを使用してモデルをプッシュします:

```py
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
)
```

## 追加のリソース

* timm (pytorch-image-models) [GitHub リポジトリ](https://github.com/rwightman/pytorch-image-models)。
* timmの[ドキュメント](https://huggingface.co/docs/timm)。
* [Aman Arora](https://github.com/amaarora) による [timmdocs](https://timm.fast.ai) での追加ドキュメント。
* [PyTorch Image Models (timm) の入門: 実務者向けガイド](https://towardsdatascience.com/getting-started-with-pytorch-image-models-timm-a-practitioners-guide-4e77b4bf9055) 著: [Chris Hughes](https://github.com/Chris-hughes10)

