transformer模型首次体验代码

发布时间 2023-08-24 09:16:05作者: 立体风

首先是安装python,更新pip源到清华源。安装transformer

pip install transformer

安装jupyter lab,也简单一行

pip install jupyterlab

现在不想用anaconda了,因为国内没有源了,国外的又慢。直接用pip吧。

然后开始体验之旅吧:

打开终端,输入:

jupyter lab

会弹出一个web页面,代开后输入python代码:

from transformers import pipeline
cf = pipeline("sentiment-analysis")
cf(
    ["hello world.",
     "This place is too dirty.",
    ]
)

输出下面的内容:

No model was supplied, defaulted to distilbert-base-uncased-finetuned-sst-2-english and revision af0f99b (https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english).
Using a pipeline without specifying a model name and revision in production is not recommended.(这里是一个警告,没关系)
[{'label': 'POSITIVE', 'score': 0.9997791647911072}, 
 {'label': 'NEGATIVE', 'score': 0.999772846698761}]

输出包含了这两句话的正面还是负面情绪的判断。可以自己写两句看看哦。

 注意:代码最后一段的是调用cf,所以没有“=”号,要注意,我一开始就是多添加一个“=”,半天看不出哪里错了。