hugging face里面有许多模型,很多人都会通过调用它的模型,那么怎么调用呢,下面是几种访问方式:
一、在线匿名访问(可能不成功)
import requests
# 访问链接是huggingface的官网中间插入api-inference,在models后面粘贴你在访问的模块名
API_URL = "https://api-inference.huggingface.co/models/uer/get2-chinese-cluecorpussmall"
# 不使用API-TOKEN直接匿名访问
response = requests.post(API_URL,json={"inputs":"你好,huggingface"})
print(response())
二、在线使用token访问(成功率高)
import requests
#使用API_TOKEN 在huggingface平台会给每个人分配一个token,申请后保存好即可
API_URL=""https://api-inference.huggingface.co/models/gpt2"
API_TOKEN = "******************"
headers = {"Authorization":f"Bearer{API_TOKEN}"}
# 接下来就可以发送文本生成请求了
response = requests.post(API_URL,headers=headers,json={"inputs":"hello, hugging face"})
print(response.json())
三、下载到本地通过磁盘访问
from transformers imjport AutoModelForCausalLM, AutoTokenizer
# 下载自己要用的模型和分词器 并保存到指定目录
model_name = "uer/gpt2"
cache_dir = "./my_model_cache/uer/gpt2"
# 下载模型
AutoModelForCausalLM.from_pretrained(model_name,cache_dir=cache_dir)
# 下载分词器
AutoTokenizer.from_pretrained(model_name,cache_dir=cache_dir)
print(f"模型和分词器已下载到:{cache_dir}")
四、将模型下载到指定位置后通过绝对路径的方式访问
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
# 访问放置模型的绝对路径(包含config.json文件的目录)
model_dir = r"你的绝对路径位置"
# 加载模型和分词器
model = AutoModelForCausalLM.from_pretrained(model_dir)
tokenizer = AutoTokenizer.from_pretrained(model_dir)
# 使用加载的模型和分词器创建生成文本的的pipeline device指定模型运行的设备为"cpu"或者"cuda"
generator = pipeline("text-generation",model = model,tokenizer = tokenizer,device = "cpu")
# 实现文本生成
output = generator("你好,我是一款语言模型",max_length=50,num_return_sequences=1)
print(output)
这是我用cpu运行出来的结果:
总体来说还是不错的啦!希望你也可以使用愉快!