文章转自 Hugging face 预训练模型
Hugging face 简介
Hugging face 是一个专注于 NLP 的公司,拥有一个开源的预训练模型库 Transformers
,里面囊括了非常多的模型例如 BERT
GPT
等
模型库
官网的模型库的地址如下:https://huggingface.co/models
使用模型
首先需要安装 transformers
库,使用以下命令安装:
- pip install transformers
接下来在代码中调用 AutoTokenizer.from_pretrained
和 AutoModel.from_pretrained
即可例如:
- from transformers import *
- model_name = 'hfl/chinese-xlnet-base'
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- model = AutoModel.from_pretrained(model_name)
运行后系统会自动下载相关的模型文件并存放在电脑中:
使用 Windows 模型保存的路径在 C:\Users\[用户名]\.cache\torch\transformers\
目录下,根据模型的不同下载的东西也不相同
使用 Linux 模型保存的路径在 ~/.cache/torch/transformers/
目录下
存在的问题
这些前提是你的电脑有网络可以直接使用代码下载相应的模型文件,但是问题是有些机器是没有外网连接权限或者下载速度非常慢。
这时候就需要把模型文件下载后在导入代码中,还是以刚才的 hfl/chinese-xlnet-base
模型为例,直接在官网搜索模型,点击进入模型的详情界面
在界面中找到 List all files in model
把弹窗内的文件全部下载下来
我们假设文件保存在 E:\models\hfl\chinese-xlnet-base\
目录下
我们只需要把 model_name
修改为下载的文件夹即可
- from transformers import *
- model_name = 'E:/models/hfl/chinese-xlnet-base/'
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- model = AutoModel.from_pretrained(model_name)
这样问题就解决了,linux 同理这里就不再赘述
在,我有一个问题就是。对于预训练模型文件的加载,源码中使用 model_name_or_path, 生成一个 static_dict 模型结构信息。这我明白。然后源码中还做了一个集合 pre model 的 Config 实例做了 pre model 的实例化操作。得到一个 model 数据信息。这个我也明白。但是这个 model 和 static_dict 之间是什么关系,代码怎么结合起来的我没看懂。看到源码的日志信息只是给出了一个 "f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at {pretrained_model_name_or_path}.n"
f"If your task is similar to the task the model of the checkpoint was trained on," f"you can already use {model.__class__.__name__} for predictions without further training."" 这样的叙述。刚才得到的两个数据之间是怎么作用的啊。还请楼主不吝赐教.之前就是一直下载下来,发现老是报错,查了路径没错
我是之前直接浏览器下载下来,这样容易出问题。
老老实实 git
怎么 git 啊,我也想试试