2

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

#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()

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

prediction = model.predict(text)

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

4

3 回答 3

2

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

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

# 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)

在执行此循环之后,预测将包含 logits,即在任何形式的标准化之前来自模型的概率分布。您可以使用以下内容从 logits 中选择得分最高的标签,并生成分类报告

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 类,该类将包含用于处理标记化、创建数据加载器、运行预测等的不同方法和变量。

于 2021-10-24T16:31:29.020 回答
1

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

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

于 2021-10-24T21:26:12.093 回答
0

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

from transformers import pipeline
classifier = pipeline('sentiment-analysis')

然后你可以使用它:

classifier("I hate this book")
于 2021-10-24T15:06:29.863 回答