【发布时间】:2021-12-17 13:33:50
【问题描述】:
我正在预测具有正面、负面和中性类别的推文的情绪分析。我已经使用 Hugging Face 训练了一个 BERT 模型。现在我想对未标记 Twitter 文本的数据框进行预测,但遇到了困难。
我已按照以下教程 (https://curiousily.com/posts/sentiment-analysis-with-bert-and-hugging-face-using-pytorch-and-python/) 进行操作,并能够使用 Hugging Face 训练 BERT 模型。
这是一个预测原始文本的示例,但它只有一个句子,我想使用一列推文。 https://curiousily.com/posts/sentiment-analysis-with-bert-and-hugging-face-using-pytorch-and-python/#predicting-on-raw-text
review_text = "I love completing my todos! Best app ever!!!"
encoded_review = tokenizer.encode_plus(
review_text,
max_length=MAX_LEN,
add_special_tokens=True,
return_token_type_ids=False,
pad_to_max_length=True,
return_attention_mask=True,
return_tensors='pt',
)
input_ids = encoded_review['input_ids'].to(device)
attention_mask = encoded_review['attention_mask'].to(device)
output = model(input_ids, attention_mask)
_, prediction = torch.max(output, dim=1)
print(f'Review text: {review_text}')
print(f'Sentiment : {class_names[prediction]}')
Review text: I love completing my todos! Best app ever!!!
Sentiment : positive
比尔的反应有效。这是解决方案。
def predictionPipeline(text):
encoded_review = tokenizer.encode_plus(
text,
max_length=MAX_LEN,
add_special_tokens=True,
return_token_type_ids=False,
pad_to_max_length=True,
return_attention_mask=True,
return_tensors='pt',
)
input_ids = encoded_review['input_ids'].to(device)
attention_mask = encoded_review['attention_mask'].to(device)
output = model(input_ids, attention_mask)
_, prediction = torch.max(output, dim=1)
return(class_names[prediction])
df2['prediction']=df2['cleaned_tweet'].apply(predictionPipeline)
【问题讨论】:
标签: pytorch sentiment-analysis huggingface-transformers pytorch-dataloader