首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用DistilBERT Huggingface NLP模型对新数据进行情感分析?

如何使用DistilBERT Huggingface NLP模型对新数据进行情感分析?
EN

Stack Overflow用户
提问于 2021-10-24 14:53:15
回答 3查看 547关注 0票数 2

我正在使用DistilBERT对我的数据集进行情感分析。数据集包含文本和每一行的标签,用于标识文本是正面的还是负面的电影评论(例如:1=正面,0=负面)。下面是huggingface文档(https://huggingface.co/transformers/custom_datasets.html?highlight=imdb)中的代码

代码语言:javascript
复制
#This dataset can be explored in the Hugging Face model hub (IMDb), and can be alternatively downloaded with the  Datasets library with load_dataset("imdb").


wget http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
tar -xf aclImdb_v1.tar.gz


#This data is organized into pos and neg folders with one text file per example. Let’s write a function that can read this in.

from pathlib import Path

def read_imdb_split(split_dir):
    split_dir = Path(split_dir)
    texts = []
    labels = []
    for label_dir in ["pos", "neg"]:
        for text_file in (split_dir/label_dir).iterdir():
            texts.append(text_file.read_text())
            labels.append(0 if label_dir is "neg" else 1)

    return texts, labels

train_texts, train_labels = read_imdb_split('aclImdb/train')
test_texts, test_labels = read_imdb_split('aclImdb/test')

from sklearn.model_selection import train_test_split
train_texts, val_texts, train_labels, val_labels = train_test_split(train_texts, train_labels, test_size=.2)

from transformers import DistilBertTokenizerFast
tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-uncased')

train_encodings = tokenizer(train_texts, truncation=True, padding=True)
val_encodings = tokenizer(val_texts, truncation=True, padding=True)
test_encodings = tokenizer(test_texts, truncation=True, padding=True)

import torch

class IMDbDataset(torch.utils.data.Dataset):
    def __init__(self, encodings, labels):
        self.encodings = encodings
        self.labels = labels

    def __getitem__(self, idx):
        item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
        item['labels'] = torch.tensor(self.labels[idx])
        return item

    def __len__(self):
        return len(self.labels)

train_dataset = IMDbDataset(train_encodings, train_labels)
val_dataset = IMDbDataset(val_encodings, val_labels)
test_dataset = IMDbDataset(test_encodings, test_labels)

#Now that our datasets our ready, we can fine-tune a model either #with the  Trainer/TFTrainer or with native PyTorch/TensorFlow. See #training.

#Fine-tuning with Trainer

#The steps above prepared the datasets in the way that the trainer is #expected. Now all we need to do is create a model to fine-tune, #define the TrainingArguments/TFTrainingArguments and instantiate a #Trainer/TFTrainer.

from transformers import DistilBertForSequenceClassification, Trainer, TrainingArguments

training_args = TrainingArguments(
    output_dir='./results',          # output directory
    num_train_epochs=3,              # total number of training epochs
    per_device_train_batch_size=16,  # batch size per device during training
    per_device_eval_batch_size=64,   # batch size for evaluation
    warmup_steps=500,                # number of warmup steps for learning rate scheduler
    weight_decay=0.01,               # strength of weight decay
    logging_dir='./logs',            # directory for storing logs
    logging_steps=10,
)

model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")

trainer = Trainer(
    model=model,                         # the instantiated  Transformers model to be trained
    args=training_args,                  # training arguments, defined above
    train_dataset=train_dataset,         # training dataset
    eval_dataset=val_dataset             # evaluation dataset
)

trainer.train()


#We can also train with Pytorch/Tensorflow

from torch.utils.data import DataLoader
from transformers import DistilBertForSequenceClassification, AdamW

device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')

model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased')
model.to(device)
model.train()

train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True)

optim = AdamW(model.parameters(), lr=5e-5)

for epoch in range(3):
    for batch in train_loader:
        optim.zero_grad()
        input_ids = batch['input_ids'].to(device)
        attention_mask = batch['attention_mask'].to(device)
        labels = batch['labels'].to(device)
        outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
        loss = outputs[0]
        loss.backward()
        optim.step()

model.eval()

我想知道在一个新的数据上测试这个模型。因此,我有一个数据帧,其中包含每一行的一段文本/评论,并且我想预测标签。有人知道我会怎么做吗?我很抱歉,我对此非常陌生,非常感谢任何帮助!我试着接收文本,清理它,然后做

代码语言:javascript
复制
prediction = model.predict(text)

我收到一个错误,说DistilBERT没有.predict属性。

EN

回答 3

Stack Overflow用户

发布于 2021-10-24 16:31:29

您从文档中分享的代码基本上涵盖了训练和评估循环。请注意,您的共享代码包含两种微调方式,一种是使用训练器,它也包括评估;另一种是使用本机Pytorch/TF,它只包含训练部分,而不包含评估部分。

下面是如何调整本机方法以在测试集上生成预测:

代码语言:javascript
复制
# Put model in evaluation mode
model.eval()

# Tracking variables for storing ground truth and predictions 
predictions , true_labels = [], []

# Prediction Loop
for batch in test_dataset:

 
 
  # Unpack the inputs from our dataloader and move to GPU/accelerator 
 
  input_ids = batch['input_ids'].to(device)
  attention_mask = batch['attention_mask'].to(device)
  labels = batch['labels'].to(device)

  
  # Telling the model not to compute or store gradients, saving memory and 
  # speeding up prediction
  with torch.no_grad():
      # Forward pass, calculate logit predictions
      outputs = model(input_ids, attention_mask=attention_mask, 
                         labels=labels)

  logits = outputs[0]

  # Move logits and labels to CPU
  logits = logits.detach().cpu().numpy()
  label_ids = labels.to('cpu').numpy()
  
  # Store predictions and true labels
  predictions.append(logits)
  true_labels.append(label_ids)

在执行此循环之后,predictions将包含logit,即在任何形式的归一化之前来自模型的概率分布。您可以使用以下命令从日志中挑选得分最高的标签,并生成分类报告

代码语言:javascript
复制
from sklearn.metrics import classification_report, accuracy_score 

# Combine the results across all batches. 
flat_predictions = np.concatenate(predictions, axis=0)

# For each sample, pick the label (0 or 1) with the higher score.
flat_predictions = np.argmax(flat_predictions, axis=1).flatten()

# Combine the correct labels for each batch into a single list.
flat_true_labels = np.concatenate(true_labels, axis=0)

# Accuracy 
print(accuracy_score(flat_true_labels, flat_predictions))

# Classification Report
report = classification_report(flat_true_labels, flat_predictions)

对于一种更优雅的执行预测的方式,您可以创建一个BERTModel类,它将包含不同的方法和变量,用于处理标记化、创建数据加载器、运行预测等。

票数 2
EN

Stack Overflow用户

发布于 2021-10-24 21:26:12

您可以尝试类似以下示例的代码:Link-BERT

您将根据BERT模型排列数据集。D部分在此链接中,您只能更改模型名称和数据集。

票数 1
EN

Stack Overflow用户

发布于 2021-10-24 15:06:30

如果您只想使用模型,您可以使用相应的管道:

代码语言:javascript
复制
from transformers import pipeline
classifier = pipeline('sentiment-analysis')

然后你就可以使用它了:

代码语言:javascript
复制
classifier("I hate this book")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69697917

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档