# 在 Hugging Face 上使用 Stable-Baselines3

`stable-baselines3` 是一组基于 PyTorch 的强化学习算法的可靠实现。

## 在 Hub 中探索 Stable-Baselines3

您可以在[模型页面](https://huggingface.co/models?library=stable-baselines3)左侧进行筛选，以查找 Stable-Baselines3 模型。

Hub 上的所有模型都附带了实用功能：
1. 自动生成的模型卡片，包含描述、训练配置等更多内容。
2. 有助于提高可发现性的元数据标签。
3. 用于与其他模型比较的评估结果。
4. 一个视频小部件，您可以在其中观看您的智能体执行操作。

## 安装该库

要安装 `stable-baselines3` 库，您需要安装两个软件包：
- `stable-baselines3`：Stable-Baselines3 库。
- `huggingface-sb3`：用于从 Hub 加载和上传 Stable-baselines3 模型的附加代码。

```
pip install stable-baselines3
pip install huggingface-sb3
```

## 使用现有模型
您可以简单地使用 `load_from_hub` 函数从 Hub 下载模型

```
checkpoint = load_from_hub(
    repo_id="sb3/demo-hf-CartPole-v1",
    filename="ppo-CartPole-v1.zip",
)
```

您需要定义两个参数：
- `--repo-id`：要下载的 Hugging Face 仓库的名称。
- `--filename`：要下载的文件。

## 共享您的模型
您可以使用以下两个不同的函数轻松上传您的模型：

1. `package_to_hub()`：在将完整仓库推送到 Hub 之前，保存模型、对其进行评估、生成模型卡片并录制智能体的回放视频。

```
package_to_hub(model=model, 
               model_name="ppo-LunarLander-v2",
               model_architecture="PPO",
               env_id=env_id,
               eval_env=eval_env,
               repo_id="ThomasSimonini/ppo-LunarLander-v2",
               commit_message="Test commit")
```

您需要定义七个参数：
- `--model`：你训练好的模型。
- `--model_architecture`：您的模型架构的名称（DQN、PPO、A2C、SAC 等）。
- `--env_id`：环境的名称。
- `--eval_env`：用于评估智能体的环境。
- `--repo-id`：要创建或更新的 Hugging Face 仓库的名称。格式为 `<your huggingface username>/<the repo name>`。
- `--commit-message`.
- `--filename`：要推送到 Hub 的文件。

2. `push_to_hub()`：将文件推送到 Hub

```
push_to_hub(
    repo_id="ThomasSimonini/ppo-LunarLander-v2",
    filename="ppo-LunarLander-v2.zip",
    commit_message="Added LunarLander-v2 model trained with PPO",
)
```
您需要定义三个参数：
- `--repo-id`：要创建或更新的 Hugging Face 仓库的名称。格式为 `<your huggingface username>/<the repo name>`。
- `--filename`：要推送到 Hub 的文件。
- `--commit-message`.

## 其他资源

* Hugging Face Stable-Baselines3 [文档](https://github.com/huggingface/huggingface_sb3#hugging-face--x-stable-baselines3-v20)
* Stable-Baselines3 [文档](https://stable-baselines3.readthedocs.io/en/master/)

