站点图标 AI技术聚合

NotImplementedError: Module is missing the required “forward“ function

在做中文文本情感分析model类定义的时候报错如下:

有两种可能:

1.重写父类函数时,函数名称写错,我将写成了 最终导致程序报错:

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

class Model(nn.Module):
    def __init__(self,config):
        super(Model, self).__init__()
        self.embeding = nn.Embedding(config.n_vocab, config.embed_size,padding_idx=config.n_vocab - 1)
        self.lstm = nn.LSTM(config.embed_size, config.hidden_size,
config.num_layers,
bidirectional=True,batch_first=True,
dropout=config.dropout)
        self.maxpool = nn.MaxPool1d(config.pad_size)
        self.fc = nn.Linear(config.hidden_size * 2 + config.embed_size, config.num_classes)
        self.softmax = nn.Softmax(dim=1)

    def forword(self,x):
        embed = self.embeding(x)
        out,_ = self.lstm(embed)
        out = torch.cat((embed,out),2)
        out = F.relu(out)
        out = out.permute(0,2,1)
        out = self.maxpool(out).reshape(out.size()[0],-1)
        out = self.fc(out)
        out = self.softmax(out)
        return out

if __name__ == "__main__":
    from configs import Config

    cfg = Config()
    cfg.pad_size = 640
    model_textcls = Model(config = cfg)
    input_tensor = torch.tensor([i for i in range(640)]).reshape([1,640])
    out_tensor = model_textcls.forward(input_tensor)
    print(out_tensor.size())
    print(out_tensor)

2.def forward函数与def __init__(self,config):一定要对齐。

文章出处登录后可见!

已经登录?立即刷新
退出移动版