使用pytorch定义自己的模型是继承nn.Module实现的。在__init__方法中定义需要初始化的参数,一般把网络中具有可学习参数的层放在这里定义。forward方法实现模型的功能,实现各个层之间的连接关系的核心。backward函数就会被自动实现(利用Autograd)。
class WordAveragingModel(nn.Module):def __init__(self, vocab_size: int, embed_dim: int, embed_dropout: float = 0.25,pad_idx: int = Vocabulary.pad_idx):......def forward(self, input_ids: torch.LongTensor, attention_mask: torch.LongTensor) -> Output:......
模型实例化
word_avg = WordAveragingModel(len(vocab), embed_dim=EMBED_DIM,
embed_dropout=DROPOUT) 这里传入的参数类型、个数是由构造函数定义的。
模型前向计算
tokenized = {“input_ids”:xxxxxxxxxxxxxx,“attention_mask”:hhhhhhhhhhhh}
y=word_avg(**tokenized)
参数tokenized包含的参数名称、类型是由forward方法定义的。
因为在Python中只要定义类型的时候,实现__call__函数,这个类型就成为可调用的。 换句话说,我们可以把这个类型的对象当作函数来使用。nn.Module的__call__自动调用了forward方法。
再说tokenized,肯定来自于数据集,是一次批处理的数据。