RNNLanguageModel的forward方法的作用是什么?

问题描述

我正在阅读有关使用AllenNlp框架的基于字符的神经网络的教程,目标是建立一个可以完成一个句子的模型。之后,我想训练我的模型,因此需要执行实例构建的步骤。我有下面的代码,我不明白转发功能的作用,有人可以帮助吗?有人可以提供一个例子

class RNNLanguageModel(Model):
def __init__(self,embedder: TextFieldEmbedder,hidden_size: int,max_len: int,vocab: Vocabulary) -> None:
    super().__init__(vocab)

    self.embedder = embedder

    # initialize a Seq2Seq encoder,LSTM
    self.rnn = PytorchSeq2SeqWrapper(
        torch.nn.LSTM(EMBEDDING_SIZE,HIDDEN_SIZE,batch_first=True))

    self.hidden2out = torch.nn.Linear(in_features=self.rnn.get_output_dim(),out_features=vocab.get_vocab_size('tokens'))
    self.hidden_size = hidden_size
    self.max_len = max_len

def forward(self,input_tokens,output_tokens):
    '''
    This is the main process of the Model where the actual computation happens. 
    Each Instance is fed to the forward method. 
    It takes dicts of tensors as input,with same keys as the fields in your Instance (input_tokens,output_tokens)
    It outputs the results of predicted tokens and the evaluation metrics as a dictionary. 
    '''

    mask = get_text_field_mask(input_tokens)
    embeddings = self.embedder(input_tokens)
    rnn_hidden = self.rnn(embeddings,mask)
    out_logits = self.hidden2out(rnn_hidden)
    loss = sequence_cross_entropy_with_logits(out_logits,output_tokens['tokens'],mask)

    return {'loss': loss}

解决方法

forward()方法是我们实现模型的“前向传递”的地方。这决定了输入(您的数据)如何流经模型以产生输出和损失值。

forward()方法必须由从PyTorch Module继承的任何类(例如AllenNLP的Model类)实现。

AllenNLP最终只是PyTorch的高级包装,因此,如果您对此感到困惑,建议您先熟悉PyTorch:https://pytorch.org/tutorials/

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...