注:看了许多种任务,机器翻译,实体命名识别,对话系统。有趣的是虽然网络结构都大同小异基本上都是seq2seq,但是里面的语句处理部分每位作者真是—八仙过海各显神通【其实算法思想都差不多,只不过调用的函数五花八门】
对流程熟悉的人应该都了解在整个训练过程中为了提高速度,都会采用mini_batch。随之而来的问题
便是一个batch中的句子不可能长度都相等,这样就给数据的规范化带来了不便,这是便需要掩码操作了【生成binary matrix】,这里提供三种方法…【使用torch】
import torch
from torch.autograd import Variable
def sequence_mask(sequence_length, max_len=None): # sequence_length :(batch_size, )
if max_len is None:
max_len = sequence_length.data.max() # 找出最长的句子
batch_size = sequence_length.size(0) # 得到batch_size
seq_range = torch.arange(0, max_len).long()
seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
seq_range_expand = Variable(seq_range_expand)
if sequence_length.is_cuda:
seq_range_expand = seq_range_expand.cuda()
seq_length_expand = (sequence_length.unsqueeze(1)
.expand_as(seq_range_expand))
return seq_range_expand < seq_length_expand # 返回binary_matrix
这样对初学者可能不太友好,我拆分了一下,方便清楚每个函数的作用,看下代码
sequence_length = torch.LongTensor([10,8,6,3,7]).cuda() # 假设batch_size为5的输入
batch_size = sequence_length.size(0) #获得batch_size
max_len = sequence_length.data.max() #获得最大长度
seq_range = torch.arange(0,max_len).long() #此函数和numpy相同,不知道numpy的sorry ):
seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len) # 涉及到了 unsequeeze和expand函数,自行去torch官网查看
seq_range_expand = seq_range_expand.cuda() #转换至gpu上
seq_length_expand = sequence_length.unsqueeze(1).expand_as(seq_range_expand) # expand_as 函数
print(seq_range_expand)
print(seq_length_expand)
print(seq_range_expand < seq_length_expand)
-----------------------------------------------------------------------------------
tensor([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], device='cuda:0')
tensor([[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8],
[ 6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]], device='cuda:0')
tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 0, 0, 0]], device='cuda:0', dtype=torch.uint8)
这就可以直观的看出 返回了一个binary matrix,这样既保证了数据形式的统一,也不会对RNN造成困扰
def generate_sent_masks(self, enc_hiddens: torch.Tensor, source_lengths: List[int]) -> torch.Tensor:
""" Generate sentence masks for encoder hidden states.
@param enc_hiddens (Tensor): encodings of shape (b, src_len, 2*h), where b = batch size,
src_len = max source length, h = hidden size.
@param source_lengths (List[int]): List of actual lengths for each of the sentences in the batch.
@returns enc_masks (Tensor): Tensor of sentence masks of shape (b, src_len),
where src_len = max source length, h = hidden size.
"""
enc_masks = torch.zeros(enc_hiddens.size(0), enc_hiddens.size(1), dtype=torch.float)
for e_id, src_len in enumerate(source_lengths): # 相较于上一个方法,直接使用了enumerate方法
enc_masks[e_id, src_len:] = 1 # 核心
return enc_masks.to(self.device)