对pytorch网络层结构的数组化详解
Python  /  管理员 发布于 5年前   160
最近再写openpose,它的网络结构是多阶段的网络,所以写网络的时候很想用列表的方式,但是直接使用列表不能将网络中相应的部分放入到cuda中去。
其实这个问题很简单的,使用moduleList就好了。
1 我先是定义了一个函数,用来根据超参数,建立一个基础网络结构
stage = [[3, 3, 3, 1, 1], [7, 7, 7, 7, 7, 1, 1]]branches_cfg = [[[128, 128, 128, 512, 38], [128, 128, 128, 512, 19]], [[128, 128, 128, 128, 128, 128, 38], [128, 128, 128, 128, 128, 128, 19]]]# used for add two branches as well as adapt to certain stagedef add_extra(i, branches_cfg, stage): """ only add CNN of brancdes S & L in stage Ti at the end of net :param in_channels:the input channels & out :param stage: size of filter :param branches_cfg: channels of image :return:list of layers """ in_channels = i layers = [] for k in range(len(stage)): padding = stage[k] // 2 conv2d = nn.Conv2d(in_channels, branches_cfg[k], kernel_size=stage[k], padding=padding) layers += [conv2d, nn.ReLU(inplace=True)] in_channels = branches_cfg[k] return layers
2 然后用普通列表装载他们
conf_bra_list = []paf_bra_list = []# param for branch networkin_channels = 128for i in range(all_stage): if i > 0: branches = branches_cfg[1] conv_sz = stage[1] else: branches = branches_cfg[0] conv_sz = stage[0] conf_bra_list.append(nn.Sequential(*add_extra(in_channels, branches[0], conv_sz))) paf_bra_list.append(nn.Sequential(*add_extra(in_channels, branches[1], conv_sz))) in_channels = 185
3 再然后,使用moduleList方法,把普通列表专成pytorch下的模块
# to listself.conf_bra = nn.ModuleList(conf_bra_list)self.paf_bra = nn.ModuleList(paf_bra_list)
4 最后,调用就好了
out_0 = x# the base transformfor k in range(len(self.vgg)): out_0 = self.vgg[k](out_0)# local name spacename = locals()confs = []pafs = []outs = []length = len(self.conf_bra)for i in range(length): name['conf_%s' % (i + 1)] = self.conf_bra[i](name['out_%s' % i]) name['paf_%s' % (i + 1)] = self.paf_bra[i](name['out_%s' % i]) name['out_%s' % (i + 1)] = torch.cat([name['conf_%s' % (i + 1)], name['paf_%s' % (i + 1)], out_0], 1) confs.append('conf_%s' % (i + 1)) pafs.append('paf_%s' % (i + 1)) outs.append('out_%s' % (i + 1))
5 顺便装了一下,使用了python局部变量命名空间,name = locals(),其实完全使用普通列表保存变量就好了,高兴就好。
以上这篇对pytorch网络层结构的数组化详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号