• bert ranking pairwise demo


    下面是用bert 训练pairwise rank 的 demo

    1. import torch
    2. from torch.utils.data import DataLoader, Dataset
    3. from transformers import BertModel, BertTokenizer
    4. from sklearn.metrics import pairwise_distances_argmin_min
    5. class PairwiseRankingDataset(Dataset):
    6. def __init__(self, sentence_pairs, tokenizer, max_length):
    7. self.input_ids = []
    8. self.attention_masks = []
    9. for pair in sentence_pairs:
    10. encoded_pair = tokenizer(pair, padding='max_length', truncation=True, max_length=max_length, return_tensors='pt')
    11. self.input_ids.append(encoded_pair['input_ids'])
    12. self.attention_masks.append(encoded_pair['attention_mask'])
    13. self.input_ids = torch.cat(self.input_ids, dim=0)
    14. self.attention_masks = torch.cat(self.attention_masks, dim=0)
    15. def __len__(self):
    16. return len(self.input_ids)
    17. def __getitem__(self, idx):
    18. input_id = self.input_ids[idx]
    19. attention_mask = self.attention_masks[idx]
    20. return input_id, attention_mask
    21. class BERTPairwiseRankingModel(torch.nn.Module):
    22. def __init__(self, bert_model_name):
    23. super(BERTPairwiseRankingModel, self).__init__()
    24. self.bert = BertModel.from_pretrained(bert_model_name)
    25. self.dropout = torch.nn.Dropout(0.1)
    26. self.fc = torch.nn.Linear(self.bert.config.hidden_size, 1)
    27. def forward(self, input_ids, attention_mask):
    28. outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
    29. pooled_output = self.dropout(outputs[1])
    30. logits = self.fc(pooled_output)
    31. return logits.squeeze()
    32. # 初始化BERT模型和分词器
    33. bert_model_name = 'bert-base-uncased'
    34. tokenizer = BertTokenizer.from_pretrained(bert_model_name)
    35. # 示例输入数据
    36. sentence_pairs = [
    37. ('I like cats', 'I like dogs'),
    38. ('The sun is shining', 'It is raining'),
    39. ('Apple is a fruit', 'Car is a vehicle')
    40. ]
    41. # 超参数
    42. batch_size = 8
    43. max_length = 128
    44. learning_rate = 1e-5
    45. num_epochs = 5
    46. # 创建数据集和数据加载器
    47. dataset = PairwiseRankingDataset(sentence_pairs, tokenizer, max_length)
    48. dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
    49. # 初始化模型并加载预训练权重
    50. model = BERTPairwiseRankingModel(bert_model_name)
    51. optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
    52. # 训练模型
    53. model.train()
    54. for epoch in range(num_epochs):
    55. total_loss = 0
    56. for input_ids, attention_masks in dataloader:
    57. optimizer.zero_grad()
    58. logits = model(input_ids, attention_masks)
    59. # 计算损失函数(使用对比损失函数)
    60. pos_scores = logits[::2] # 正样本分数
    61. neg_scores = logits[1::2] # 负样本分数
    62. loss = torch.relu(1 - pos_scores + neg_scores).mean()
    63. total_loss += loss.item()
    64. loss.backward()
    65. optimizer.step()
    66. print(f"Epoch {epoch+1}/{num_epochs} - Loss: {total_loss:.4f}")
    67. # 推断模型
    68. model.eval()
    69. with torch.no_grad():
    70. embeddings = model.bert.embeddings.word_embeddings(dataset.input_ids)
    71. pairwise_distances = pairwise_distances_argmin_min(embeddings.numpy())
    72. # 输出结果
    73. for i, pair in enumerate(sentence_pairs):
    74. pos_idx = pairwise_distances[0][2 * i]
    75. neg_idx = pairwise_distances[0][2 * i + 1]
    76. pos_dist = pairwise_distances[1][2 * i]
    77. neg_dist = pairwise_distances[1][2 * i + 1]
    78. print(f"Pair: {pair}")
    79. print(f"Positive example index: {pos_idx}, Distance: {pos_dist:.4f}")
    80. print(f"Negative example index: {neg_idx}, Distance: {neg_dist:.4f}")
    81. print()

  • 相关阅读:
    阿里云/腾讯云国际站代理:阿里云服务器介绍
    和数集团“区块链+数字化”促进新场景应用落地 为多领域开启无限可能
    2023 年KPI (KPI:Key Performance Indicator) review
    Java基础
    Mybatis动态SQL和分页
    码蹄杯语言基础:选择结构(C语言)
    RabbitMQ+SpringBoot企业版队列实战------【华为云版】
    在CDH的hue上的oozie出现,提交 Coordinator My Schedule 时出错
    mysql 触发器
    【0103】【内存上下文】重置内存上下文(AllocSetReset)
  • 原文地址:https://blog.csdn.net/jp_666/article/details/132759543