변환기에서 AutoTokenizer 및 AutoModel의 원리 분석(1)

감정 분석의 예를 들어 변환기에서 AutoTokenizer 및 AutoModel을 분석합니다.

通过ipython 行查看sentiment-analynise依赖的Hugging Face – 미래를 구축하는 AI 커뮤니티. 우리는 오픈 소스와 오픈 사이언스를 통해 인공 지능을 발전시키고 민주화하는 여정에 있습니다. https://huggingface.co/

다음 위치의 라이브러리:

 위 출력에서 ​​파이프라인 모드에서 사전 훈련에 사용되는 라이브러리를 얻습니다.

distilbert-base-uncased-finetuned-sst-2-english

 AutoTokenizer의 원리 설명:

 만약에

test_sentences = ("today is not that bad", "today is so bad" , "so good")

 3개의 요소가 있으면 오류가 보고됩니다.

왜냐하면

inputs_tensor = tokenizer.encode_plus(test_sentences, padding=True, truncation=True, return_tensors="pt")

문장 in은 Tuple()에서 하나 또는 두 개의 요소여야 합니다! ! !

그리고

 tokenizer()를 사용하면 오류가 보고되지 않습니다! ! !

 기본 코드를 분석한 결과 다음과 같은 사실을 발견했습니다.

입력이 문자열인 경우 tokenizer() == tokenizer.encode_plus();

입력이 리스트나 튜플일 때, tokenizer() == tokenizer.batch_encode_plus()

 다음은 padding=True와 padding="max_length"의 차이점에 대한 설명입니다.

패딩=참:

test_sentences = ("today is not that bad", "today is so bad", "so good")

때를 의미

test_sentences에 있는 모든 문장의 길이가 다른 경우 padding은 가장 긴 문장 길이를 max_length로 사용하여 [PAD]를 채웁니다. 즉, 제로 패딩입니다.

패딩="최대_길이":

test_sentences = ("today is not that bad", "today is so bad", "so good")

 padding="max_length"는 일반적으로 max_length=XXXX 매개변수와 함께 사용되며, 제로 패딩은 max_length 길이로 수행됩니다.

tokenizer.batch_encode_plus() 또는 tokenizer.encode_plus()의 반환 값을 설명하십시오.

 input_ids: 토크나이저에 의해 인코딩된 vocab에 해당하는 id를 나타냅니다.

Attention_mask: 1은 패딩되지 않은 단어를 나타내고 0은 패딩이 있는 단어를 나타냅니다.

tokenizer.batch_encode_plus() 또는 tokenizer.encode_plus()를 사용한 기본 명령문:

tokenizer.convert_tokens_to_ids(tokenizer.tokenize(test_sentences[0]))

 토크나이저에서 동의어 사전을 확인하십시오.

 AutoModel의 원리 설명:

여기에서 사용됩니다: AutoModelForSequenceClassification

 반환 값 logits는 차원이 (3,2)인 텐서이며 처리 후 [1,0,1]을 얻습니다.

[1,0,1]은 무엇을 나타냅니까?

구성을 살펴보겠습니다.

 위에서 1은 양수를 나타내고 0은 음수를 나타냅니다.

전체 코드:

# ---encoding:utf-8---
# @Time    : 2023/8/1 10:54
# @Author  : CBAiotAigc
# @Email   :[email protected]
# @Site    : 
# @File    : tokenizer_sentiment_analysis.py
# @Project : AI_Review
# @Software: PyCharm
from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
import torch
import torch.nn as nn

model_name = "../model/distilbert-base-uncased-finetuned-sst-2-english"

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

test_sentences = ["today is not that bad", "today is so bad", "so good"]

# inputs_tensor = tokenizer.encode_plus(test_sentences, padding=True, truncation=True, return_tensors="pt")
# print(inputs_tensor)
inputs_tensor = tokenizer(test_sentences, padding=True, truncation=True, return_tensors="pt")

print(inputs_tensor)

inputs_tensor = tokenizer.batch_encode_plus(test_sentences, padding=True, truncation=True, return_tensors="pt")
print(inputs_tensor)

outputs = model(**inputs_tensor)
print(outputs)

model.eval()
with torch.no_grad():
    labels = torch.argmax(outputs.logits, dim=-1)
    print(labels)

    print(model.config.id2label)
    print([model.config.id2label[id] for id in labels.tolist()])

추천

출처blog.csdn.net/wtl1992/article/details/132037310