defcollate_fn(data):
sents =[i[0]for i in data]
labels =[i[1]for i in data]#编码
data = token.batch_encode_plus(batch_text_or_text_pairs=sents,
truncation=True,
padding='max_length',
max_length=500,
return_tensors='pt',
return_length=True)#input_ids:编码之后的数字#attention_mask:是补零的位置是0,其他位置是1
input_ids = data['input_ids']
attention_mask = data['attention_mask']
token_type_ids = data['token_type_ids']
labels = torch.LongTensor(labels)#print(data['length'], data['length'].max())return input_ids, attention_mask, token_type_ids, labels
#数据加载器
loader = torch.utils.data.DataLoader(dataset=dataset,
batch_size=16,
collate_fn=collate_fn,
shuffle=True,
drop_last=True)
classModel(torch.nn.Module):def__init__(self):super().__init__()
self.fc = torch.nn.Linear(768,2)defforward(self, input_ids, attention_mask, token_type_ids):with torch.no_grad():
out = pretrained(input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids)
out = self.fc(out.last_hidden_state[:,0])
out = out.softmax(dim=1)return out
model = Model()
classModel(torch.nn.Module):def__init__(self):super().__init__()
self.decoder = torch.nn.Linear(768, token.vocab_size, bias=False)
self.bias = torch.nn.Parameter(torch.zeros(token.vocab_size))
self.decoder.bias = self.bias
defforward(self, input_ids, attention_mask, token_type_ids):with torch.no_grad():
out = pretrained(input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids)
out = self.decoder(out.last_hidden_state[:,15])return out
model = Model()
句子关系推断
defcollate_fn(data):
sents =[i[:2]for i in data]
labels =[i[2]for i in data]#编码
data = token.batch_encode_plus(batch_text_or_text_pairs=sents,
truncation=True,
padding='max_length',
max_length=45,
return_tensors='pt',
return_length=True,
add_special_tokens=True)#input_ids:编码之后的数字#attention_mask:是补零的位置是0,其他位置是1#token_type_ids:第一个句子和特殊符号的位置是0,第二个句子的位置是1
input_ids = data['input_ids']
attention_mask = data['attention_mask']
token_type_ids = data['token_type_ids']
labels = torch.LongTensor(labels)#print(data['length'], data['length'].max())return input_ids, attention_mask, token_type_ids, labels
#数据加载器
loader = torch.utils.data.DataLoader(dataset=dataset,
batch_size=8,
collate_fn=collate_fn,
shuffle=True,
drop_last=True)
classModel(torch.nn.Module):def__init__(self):super().__init__()
self.fc = torch.nn.Linear(768,2)defforward(self, input_ids, attention_mask, token_type_ids):with torch.no_grad():
out = pretrained(input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids)
out = self.fc(out.last_hidden_state[:,0])
out = out.softmax(dim=1)return out
model = Model()