【踩坑记录】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):
		...
相关推荐
Code_流苏5 分钟前
《Python星球日记》 第54天:卷积神经网络进阶
python·cnn·数据增强·图像分类·alexnet·lenet-5·vgg
suyukangchen7 分钟前
深入理解 Linux 阻塞IO与Socket数据结构
linux·数据结构·python
泡芙萝莉酱8 分钟前
各省份发电量数据(2005-2022年)-社科数据
大数据·人工智能·深度学习·数据挖掘·数据分析·毕业论文·数据统计
threelab9 分钟前
02.three官方示例+编辑器+AI快速学习webgl_animation_skinning_blending
人工智能·学习·编辑器
sword devil90026 分钟前
Python实用工具:pdf转doc
python·pdf
zhuiQiuMX26 分钟前
笔试阶段性心得总结
java·python
未名编程1 小时前
【Flask开发踩坑实录】pip 安装报错:“No matching distribution found” 的根本原因及解决方案!
python·flask·pip
wei_shuo2 小时前
OB Cloud 云数据库V4.3:SQL +AI全新体验
数据库·人工智能·sql
努力的搬砖人.3 小时前
AI生成视频推荐
人工智能
q567315233 小时前
Node.js数据抓取技术实战示例
爬虫·python·scrapy·node.js