import torch import torch.nn as nn from transformers import BertModel, BertTokenizer,…
- User
import torch import torch.nn as nn from transformers import BertModel, BertTokenizer, BertConfig
class RelationExtractionModel(nn.Module): def init(self, pretrained_model_name, num_labels): super().init() self.bert = BertModel.from_pretrained(pretrained_model_name) self.dropout = nn.Dropout(0.1) self.classifier = nn.Linear(self.bert.config.hidden_size, num_labels)
def forward(self, input_ids, attention_mask, token_type_ids): outputs = self.bert(input_ids, attention_mask, token_type_ids) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) return logitspretrained_model_name = "bert-base-chinese" tokenizer = BertTokenizer.from_pretrained(pretrained_model_name) config = BertConfig.from_pretrained(pretrained_model_name) num_labels = 4 model = RelationExtractionModel(pretrained_model_name, num_labels)
#接下来,我们需要创建一个适当的数据加载器,并设置训练参数。更多具体代码请参考PyTorch官方文档。我们需要定义优化器、损失函数等。
from torch.optim import AdamW from torch.utils.data import DataLoader
batch_size = 8 num_epochs = 3 learning_rate = 5e-5 weight_decay = 0.01
optimizer = AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay) scheduler = None # Put your learning rate scheduler here criterion = nn.CrossEntropyLoss()
#训练过程如下:
model.train() total_steps = len(example_data) * num_epochs device = "cuda" if torch.cuda.is_available() else "cpu"
for epoch in range(num_epochs): for i, batch in enumerate(DataLoader(example_data, batch_size=batch_size)): input_ids = torch.tensor(batch['token_ids']).unsqueeze(0).to(device) print(input_ids.shape) attention_mask = torch.tensor(batch['attention_mask']).unsqueeze(0).float().to(device) token_type_ids = torch.tensor(batch['token_type_ids']).unsqueeze(0).long().to(device) labels = torch.tensor(batch['labels']).to(device)
logits = model(input_ids, attention_mask, token_type_ids) # Notice this line loss = criterion(logits, labels) optimizer.zero_grad() loss.backward() optimizer.step() scheduler.step() print(f"Epoch {epoch}/{num_epochs}, loss: {loss.item()}")以上代码报错:RuntimeError: The size of tensor a (40) must match the size of tensor b (39) at non-singleton dimension 1请修改
- Assistant
根据错误提示,张量a的大小(40)必须与张量b的大小(39)相匹配。在这个例子中,这个问题可能是由于输入数据尺寸不匹配的批处理大小(8)或者其它原因导致的。为了解决这个问题,我们需要修改数据加载器以确保提供正确大小的输入张量。
此外,根据您给出的代码片段,我注意到在创建输入张量时使用了
unsqueeze(0)。这可能是造成尺寸不匹配的原因。unsqueeze(0)会在给定张量的第一个维度前插入一个额外的维度。这可能导致输入张量的形状与模型所期望的输入尺寸不同,从而导致尺寸不匹配的错误。我建议先删除
unsqueeze(0),然后检查形状是否匹配。以下是具体实现方式:model.train() total_steps = len(example_data) * num_epochs device = "cuda" if torch.cuda.is_available() else "cpu" for epoch in range(num_epochs): for i, batch in enumerate(DataLoader(example_data, batch_size=batch_size)): # Remove unsqueeze(0) from the following lines input_ids = torch.tensor(batch['token_ids']).to(device) attention_mask = torch.tensor(batch['attention_mask']).float().to(device) token_type_ids = torch.tensor(batch['token_type_ids']).long().to(device) labels = torch.tensor(batch['labels']).to(device) logits = model(input_ids, attention_mask, token_type_ids) loss = criterion(logits, labels) optimizer.zero_grad() loss.backward() optimizer.step() scheduler.step() print(f"Epoch {epoch}/{num_epochs}, loss: {loss.item()}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.