【踩坑记录】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):
		...
相关推荐
橘子星7 分钟前
🚀 手把手带你写一个端侧 AI 应用的"加载进度条"与"聊天对话框"
前端·人工智能
武汉唯众智创22 分钟前
人工智能专业一体化教学与实训解决方案
人工智能·人工智能实训室·人工智能实训室解决方案·人工智能实验实训方案
公众号:fuwuqiBMC28 分钟前
(转自“服务器BMC”)服务器BMC芯片——多Die(芯片)封装
运维·服务器·人工智能
小猴子爱上树28 分钟前
一站式解决图片视频翻译难题的高效AI工具
人工智能·python·音视频
Summer-Bright40 分钟前
NVIDIA Vera CPU 深度解读:Olympus 自研核心为什么是 Agentic AI 的关键拼图
人工智能·ai·自然语言处理
weixin_5386019742 分钟前
智能体测开Day31
开发语言·python
yiyesushu42 分钟前
GitHub Copilot 在 vscode 中使用之 Prompt
人工智能·visual studio code
小K漫剧创作笔记44 分钟前
AI短剧出海从「选修课」变「必修课」:合规分发正在成为内容全球化的真正门槛
大数据·人工智能·ai·aigc·漫剧
蜜桃味女焊匠人1 小时前
气保焊怎样改造,稳定达成40%-60%节气降耗效果?
人工智能·经验分享·其他·机器人
lbb 小魔仙1 小时前
Git + Python 项目工作流最佳实践:pre-commit、CI、CHANGELOG 自动化
git·python·ci/cd