transformer库的使用
时间: 2023-11-28 19:45:25 浏览: 86
transformers库是一个用于自然语言处理的Python库,它提供了许多预训练的模型和用于训练自定义模型的工具。以下是transformers库的使用方法:
1.安装transformers库
```shell
pip install transformers
```
2.导入所需的模块
```python
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
```
3.使用pipeline进行文本分类
```python
classifier = pipeline('sentiment-analysis')
result = classifier('I love using transformers library!')
print(result) # 输出:[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
```
4.使用AutoTokenizer和AutoModelForSequenceClassification进行文本分类
```python
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased')
inputs = tokenizer('I love using transformers library!', return_tensors='pt')
outputs = model(**inputs)
print(outputs.logits) # 输出:tensor([[-3.1869, 3.4226]], grad_fn=<AddmmBackward>)
```
阅读全文