【踩坑记录】pytorch 自定义嵌套网络时部分网络输出不变的问题

问题描述

使用如下的自定义的多层嵌套网络进行训练:

python 复制代码
class FC1_bot(nn.Module):
    def __init__(self):
        super(FC1_bot, self).__init__()
        self.embeddings = nn.Sequential(
        	nn.Linear(10, 10)
        )
       
    def forward(self, x):
        emb = self.embeddings(x)
        return emb

    
class FC1_top(nn.Module):
    def __init__(self):
        super(FC1_top, self).__init__()
        self.prediction = nn.Sequential(
            nn.Dropout(p=0.5),
            nn.Linear(10, 10)
        )
        
    def forward(self, x):
        logit = self.prediction(x)
        return logit


class FC1(nn.Module):
    def __init__(self, num):
        super(FC1, self).__init__()
        self.num = num

        self.bot = []
        for _ in range(num):
            self.bot.append(FC1_bot())

        self.top = FC1_top()
        
        self.softmax = nn.Softmax(dim=1)

    def forward(self, x):
        x = list(x)
        emb = []
        for i in range(self.num):
            emb.append(self.bot[i](x[i]))

        agg_emb = self._aggregate(emb)
        logit = self.top(agg_emb)

        pred = self.softmax(logit)

        return emb, pred
    
    def _aggregate(self, x):
        # Note: x is a list of tensors.
        return torch.cat(x, dim=1)

训练的代码如下:

python 复制代码
def train(self):
	# train entire model
	self.model.train()

	for epoch in range(self.args.epochs):
		...

解决办法

需要把所有用到的模型都变成训练模式,否则只有top模型在被训练。

python 复制代码
def train(self):
	# train entire model
	self.model.train()
	self.model.top.train()
	for i in range(self.args.num):
	    self.model.bot[i].train()

	for epoch in range(self.args.epochs):
		...
相关推荐
tap.AI2 分钟前
Deepseek(九)多语言客服自动化:跨境电商中的多币种、多语种投诉实时处理
运维·人工智能·自动化
好奇龙猫7 分钟前
【人工智能学习-AI-MIT公开课第 20・21 概率推理】
人工智能·学习
实战项目9 分钟前
边缘计算在智慧物流中的实时跟踪应用
人工智能·边缘计算
绀目澄清12 分钟前
Unity 的AI Navigation 系统详细总结
人工智能·unity·游戏引擎
一招定胜负12 分钟前
图像形态学+边缘检测及CNN关联
人工智能·深度学习·cnn
dagouaofei12 分钟前
2026 年工作计划 PPT 制作方式对比:AI 与传统方法差异
人工智能·python·powerpoint
虚拟搬运工16 分钟前
xformers造成comfyu启动失败
python·comfyui
Hello.Reader17 分钟前
PyFlink DataStream Operators 算子分类、函数写法、类型系统、链路优化(Chaining)与工程化踩坑
前端·python·算法
Learner28 分钟前
Python函数
开发语言·python
万行33 分钟前
机器学习&第五章生成式生成器
人工智能·python·算法·机器学习