timm documentation

从 Hugging Face Hub 共享和加载模型

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

从 Hugging Face Hub 共享和加载模型

timm 库内置了与 Hugging Face Hub 的集成,方便从 🤗 Hub 共享和加载模型。

在这份简短的指南中,我们将了解如何:

  1. 在 Hub 上共享一个 timm 模型
  2. 如何从 Hub 重新加载该模型

身份验证

首先,请确保已安装 huggingface_hub 包。

pip install huggingface_hub

然后,您需要完成身份验证。您可以通过运行以下命令来实现:

hf auth login

或者,如果您使用的是 notebook,可以使用 notebook_login 辅助函数:

>>> from huggingface_hub import notebook_login
>>> notebook_login()

共享模型

>>> import timm
>>> model = timm.create_model('resnet18', pretrained=True, num_classes=4)

通常,您会在此处训练或微调模型。为了简化本教程,我们将跳过这一步。

假设我们现在已经完成了模型的微调。下一步就是将其推送到 Hub!我们可以使用 timm.models.push_to_hf_hub 函数来实现。导出的配置描述了模型当前的状态(例如,其类别数量,或者如果输入尺寸和通道数有变化的话,也会包含这些信息),请参阅 适配和导出模型。

>>> model_cfg = dict(label_names=['a', 'b', 'c', 'd'])
>>> timm.models.push_to_hf_hub(model, 'resnet18-random', model_config=model_cfg)

运行上述代码会将模型推送到 Hub 上的 <your-username>/resnet18-random。现在你可以与朋友分享此模型,或在自己的代码中使用它!

加载模型

从 Hub 加载模型只需调用 timm.create_model,传入以 hf-hub: 为前缀的 Hub 仓库名称,并设置 pretrained=True。在此示例中,我们将使用 nateraw/resnet18-random,即我们刚刚推送到 Hub 的模型。

>>> model_reloaded = timm.create_model('hf-hub:nateraw/resnet18-random', pretrained=True)
Update on GitHub