You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch多模型定义报错:实例化Model2触发TypeError问题求助

问题:PyTorch中实例化Model2报错TypeError

我想要在PyTorch中使用两个不同的模型,执行以下代码后无法成功运行第二个模型Model2,报错信息如下:

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = nn.Linear(2, 64)
        self.linear2 = nn.Linear(64, 3)

    def forward(self, x):   
        x = self.linear1(x)
        x = torch.sigmoid(x)  
        x = self.linear2(x)

        return x
                
class Model2(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = nn.Linear(2, 64)
        self.linear2 = nn.Linear(64, 1)

    def forward(self, x):   
        x = self.linear1(x)
        x = torch.sigmoid(x)  
        x = self.linear2(x)

        return x
                
net = Model()
net2 = Model2()

错误信息

TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_477/2280223066.py in <module>
     26 
     27 net = Model()
---&gt; 28 net2 = Model2()

/tmp/ipykernel_477/2280223066.py in __init__(self)
     14 class Model2(nn.Module):
     15     def __init__(self):
---&gt; 16         super(Model, self).__init__()
     17         self.linear1 = nn.Linear(2, 64)
     18         self.linear2 = nn.Linear(64, 1)

TypeError: super(type, obj): obj must be an instance or subtype of type

问题原因

Model2的__init__方法中,调用super()时传入的第一个参数错误,写成了Model,但这里必须传入当前类Model2。super()的第一个参数需要对应当前子类的类型,才能正确定位父类nn.Module的初始化方法。

修复后的代码

import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = nn.Linear(2, 64)
        self.linear2 = nn.Linear(64, 3)

    def forward(self, x):   
        x = self.linear1(x)
        x = torch.sigmoid(x)  
        x = self.linear2(x)

        return x
                
class Model2(nn.Module):
    def __init__(self):
        # 将第一个参数改为当前类Model2
        super(Model2, self).__init__()
        self.linear1 = nn.Linear(2, 64)
        self.linear2 = nn.Linear(64, 1)

    def forward(self, x):   
        x = self.linear1(x)
        x = torch.sigmoid(x)  
        x = self.linear2(x)

        return x
                
net = Model()
net2 = Model2()

更简洁的写法(Python3+)

可以使用Python3的简化语法super().__init__(),无需手动传入类名和self,避免参数写错:

class Model2(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(2, 64)
        self.linear2 = nn.Linear(64, 1)

    def forward(self, x):   
        x = self.linear1(x)
        x = torch.sigmoid(x)  
        x = self.linear2(x)

        return x

内容的提问来源于stack exchange,提问作者asdfe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:07:08