pytorch构建多模型实例


Posted in Python onJanuary 15, 2020

pytorch构建双模型

第一部分:构建"se_resnet152","DPN92()"双模型

import numpy as np
from functools import partial
import torch
from torch import nn
import torch.nn.functional as F
from torch.optim import SGD,Adam
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader

from torch.optim.optimizer import Optimizer

import torchvision
from torchvision import models
import pretrainedmodels
from pretrainedmodels.models import *
from torch import nn
from torchvision import transforms as T
import random



random.seed(2050)
np.random.seed(2050)
torch.manual_seed(2050)
torch.cuda.manual_seed_all(2050)

class FCViewer(nn.Module):
  def forward(self, x):
    return x.view(x.size(0), -1)

  
'''Dual Path Networks in PyTorch.'''
class Bottleneck(nn.Module):
  def __init__(self, last_planes, in_planes, out_planes, dense_depth, stride, first_layer):
    super(Bottleneck, self).__init__()
    self.out_planes = out_planes
    self.dense_depth = dense_depth

    self.conv1 = nn.Conv2d(last_planes, in_planes, kernel_size=1, bias=False)
    self.bn1 = nn.BatchNorm2d(in_planes)
    self.conv2 = nn.Conv2d(in_planes, in_planes, kernel_size=3, stride=stride, padding=1, groups=32, bias=False)
    self.bn2 = nn.BatchNorm2d(in_planes)
    self.conv3 = nn.Conv2d(in_planes, out_planes+dense_depth, kernel_size=1, bias=False)
    self.bn3 = nn.BatchNorm2d(out_planes+dense_depth)

    self.shortcut = nn.Sequential()
    if first_layer:
      self.shortcut = nn.Sequential(
        nn.Conv2d(last_planes, out_planes+dense_depth, kernel_size=1, stride=stride, bias=False),
        nn.BatchNorm2d(out_planes+dense_depth)
      )

  def forward(self, x):
    out = F.relu(self.bn1(self.conv1(x)))
    out = F.relu(self.bn2(self.conv2(out)))
    out = self.bn3(self.conv3(out))
    x = self.shortcut(x)
    d = self.out_planes
    out = torch.cat([x[:,:d,:,:]+out[:,:d,:,:], x[:,d:,:,:], out[:,d:,:,:]], 1)
    out = F.relu(out)
    return out


class DPN(nn.Module):
  def __init__(self, cfg):
    super(DPN, self).__init__()
    in_planes, out_planes = cfg['in_planes'], cfg['out_planes']
    num_blocks, dense_depth = cfg['num_blocks'], cfg['dense_depth']

    self.conv1 = nn.Conv2d(7, 64, kernel_size=3, stride=1, padding=1, bias=False)
    self.bn1 = nn.BatchNorm2d(64)
    self.last_planes = 64
    self.layer1 = self._make_layer(in_planes[0], out_planes[0], num_blocks[0], dense_depth[0], stride=1)
    self.layer2 = self._make_layer(in_planes[1], out_planes[1], num_blocks[1], dense_depth[1], stride=2)
    self.layer3 = self._make_layer(in_planes[2], out_planes[2], num_blocks[2], dense_depth[2], stride=2)
    self.layer4 = self._make_layer(in_planes[3], out_planes[3], num_blocks[3], dense_depth[3], stride=2)
    self.linear = nn.Linear(out_planes[3]+(num_blocks[3]+1)*dense_depth[3], 64) 
    self.bn2 = nn.BatchNorm1d(64)
  def _make_layer(self, in_planes, out_planes, num_blocks, dense_depth, stride):
    strides = [stride] + [1]*(num_blocks-1)
    layers = []
    for i,stride in enumerate(strides):
      layers.append(Bottleneck(self.last_planes, in_planes, out_planes, dense_depth, stride, i==0))
      self.last_planes = out_planes + (i+2) * dense_depth
    return nn.Sequential(*layers)

  def forward(self, x):
    out = F.relu(self.bn1(self.conv1(x)))
    out = self.layer1(out)
    out = self.layer2(out)
    out = self.layer3(out)
    out = self.layer4(out)
    out = F.avg_pool2d(out, 4)
    out = out.view(out.size(0), -1)
    out = self.linear(out)
    out= F.relu(self.bn2(out))
    return out



def DPN26():
  cfg = {
    'in_planes': (96,192,384,768),
    'out_planes': (256,512,1024,2048),
    'num_blocks': (2,2,2,2),
    'dense_depth': (16,32,24,128)
  }
  return DPN(cfg)

def DPN92():
  cfg = {
    'in_planes': (96,192,384,768),
    'out_planes': (256,512,1024,2048),
    'num_blocks': (3,4,20,3),
    'dense_depth': (16,32,24,128)
  }
  return DPN(cfg)
class MultiModalNet(nn.Module):
  def __init__(self, backbone1, backbone2, drop, pretrained=True):
    super().__init__()
    if pretrained:
      img_model = pretrainedmodels.__dict__[backbone1](num_classes=1000, pretrained='imagenet') #seresnext101
    else:
      img_model = pretrainedmodels.__dict__[backbone1](num_classes=1000, pretrained=None)
    
    self.visit_model=DPN26()
    
    self.img_encoder = list(img_model.children())[:-2]
    self.img_encoder.append(nn.AdaptiveAvgPool2d(1))
    
    self.img_encoder = nn.Sequential(*self.img_encoder)
    if drop > 0:
      self.img_fc = nn.Sequential(FCViewer(),
                  nn.Dropout(drop),
                  nn.Linear(img_model.last_linear.in_features, 512),
                  nn.BatchNorm1d(512))
                  
    else:
      self.img_fc = nn.Sequential(
        FCViewer(),
        nn.BatchNorm1d(img_model.last_linear.in_features),
        nn.Linear(img_model.last_linear.in_features, 512))
    self.bn=nn.BatchNorm1d(576)
    self.cls = nn.Linear(576,9) 

  def forward(self, x_img,x_vis):
    x_img = self.img_encoder(x_img)
    x_img = self.img_fc(x_img)
    x_vis=self.visit_model(x_vis)
    x_cat = torch.cat((x_img,x_vis),1)
    x_cat = F.relu(self.bn(x_cat))
    x_cat = self.cls(x_cat)
    return x_cat

test_x = Variable(torch.zeros(64, 7,26,24))
test_x1 = Variable(torch.zeros(64, 3,224,224))
model=MultiModalNet("se_resnet152","DPN92()",0.1)
out=model(test_x1,test_x)
print(model._modules.keys())
print(model)

print(out.shape)

第二部分构建densenet201单模型

#encoding:utf-8
import torchvision.models as models
import torch
import pretrainedmodels
from torch import nn
from torch.autograd import Variable
#model = models.resnet18(pretrained=True)
#print(model)
#print(model._modules.keys())
#feature = torch.nn.Sequential(*list(model.children())[:-2])#模型的结构
#print(feature)
'''
class FCViewer(nn.Module):
  def forward(self, x):
    return x.view(x.size(0), -1)
class M(nn.Module):
  def __init__(self, backbone1, drop, pretrained=True):
    super(M,self).__init__()
    if pretrained:
      img_model = pretrainedmodels.__dict__[backbone1](num_classes=1000, pretrained='imagenet') 
    else:
      img_model = pretrainedmodels.__dict__[backbone1](num_classes=1000, pretrained=None)
    
    self.img_encoder = list(img_model.children())[:-1]
    self.img_encoder.append(nn.AdaptiveAvgPool2d(1))
    self.img_encoder = nn.Sequential(*self.img_encoder)

    if drop > 0:
      self.img_fc = nn.Sequential(FCViewer(),
                  nn.Dropout(drop),
                  nn.Linear(img_model.last_linear.in_features, 236))
                  
    else:
      self.img_fc = nn.Sequential(
        FCViewer(),
        nn.Linear(img_model.last_linear.in_features, 236)
      )

    self.cls = nn.Linear(236,9) 

  def forward(self, x_img):
    x_img = self.img_encoder(x_img)
    x_img = self.img_fc(x_img)
    return x_img 

model1=M('densenet201',0,pretrained=True)
print(model1)
print(model1._modules.keys())
feature = torch.nn.Sequential(*list(model1.children())[:-2])#模型的结构
feature1 = torch.nn.Sequential(*list(model1.children())[:])
#print(feature)
#print(feature1)
test_x = Variable(torch.zeros(1, 3, 100, 100))
out=feature(test_x)
print(out.shape)
'''
'''
import torch.nn.functional as F
class LenetNet(nn.Module):
  def __init__(self):
    super(LenetNet, self).__init__()
    self.conv1 = nn.Conv2d(7, 6, 5) 
    self.conv2 = nn.Conv2d(6, 16, 5) 
    self.fc1  = nn.Linear(144, 120)
    self.fc2  = nn.Linear(120, 84)
    self.fc3  = nn.Linear(84, 10)
  def forward(self, x): 
    x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) 
    x = F.max_pool2d(F.relu(self.conv2(x)), 2)
    x = x.view(x.size()[0], -1) 
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)    
    return x

model1=LenetNet()
#print(model1)
#print(model1._modules.keys())
feature = torch.nn.Sequential(*list(model1.children())[:-3])#模型的结构
#feature1 = torch.nn.Sequential(*list(model1.children())[:])
print(feature)
#print(feature1)
test_x = Variable(torch.zeros(1, 7, 27, 24))
out=model1(test_x)
print(out.shape)

class FCViewer(nn.Module):
  def forward(self, x):
    return x.view(x.size(0), -1)
class M(nn.Module):
  def __init__(self):
    super(M,self).__init__()
    img_model =model1 
    self.img_encoder = list(img_model.children())[:-3]
    self.img_encoder.append(nn.AdaptiveAvgPool2d(1))
    self.img_encoder = nn.Sequential(*self.img_encoder)
    self.img_fc = nn.Sequential(FCViewer(),
		      nn.Linear(16, 236))
    self.cls = nn.Linear(236,9) 

  def forward(self, x_img):
    x_img = self.img_encoder(x_img)
    x_img = self.img_fc(x_img)
    return x_img 

model2=M()

test_x = Variable(torch.zeros(1, 7, 27, 24))
out=model2(test_x)
print(out.shape)

'''

以上这篇pytorch构建多模型实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现带验证码网站的自动登陆实现代码
Jan 12 Python
Python使用迭代器打印螺旋矩阵的思路及代码示例
Jul 02 Python
Python中__init__.py文件的作用详解
Sep 18 Python
python3实现域名查询和whois查询功能
Jun 21 Python
Python实现对文件进行单词划分并去重排序操作示例
Jul 10 Python
pandas.DataFrame删除/选取含有特定数值的行或列实例
Nov 07 Python
python 读取文件并把矩阵转成numpy的两种方法
Feb 12 Python
python多线程分块读取文件
Aug 29 Python
Python 字符串、列表、元组的截取与切片操作示例
Sep 17 Python
Python-numpy实现灰度图像的分块和合并方式
Jan 09 Python
Tensorflow 实现释放内存
Feb 03 Python
基于Python生成个性二维码过程详解
Mar 05 Python
利用Pytorch实现简单的线性回归算法
Jan 15 #Python
pytorch实现线性拟合方式
Jan 15 #Python
Python 支持向量机分类器的实现
Jan 15 #Python
pytorch-神经网络拟合曲线实例
Jan 15 #Python
Pytorch中的VGG实现修改最后一层FC
Jan 15 #Python
详解Python3 中的字符串格式化语法
Jan 15 #Python
用pytorch的nn.Module构造简单全链接层实例
Jan 14 #Python
You might like
咖啡豆分级制度 咖啡豆等级分类 咖啡豆是按口感分类的吗?
2021/03/05 新手入门
php图片加中文水印实现代码分享
2012/10/31 PHP
PHP下通过QRCode类库创建中间带网站LOGO的二维码
2014/07/12 PHP
WordPress中创建用户角色的相关PHP函数使用详解
2015/12/25 PHP
thinkPHP引入类的方法详解
2016/12/08 PHP
PHP实现通过二维数组键值获取一维键名操作示例
2019/10/11 PHP
laravel 根据不同组织加载不同视图的实现
2019/10/14 PHP
JAVASCRIPT 对象的创建与使用
2021/03/09 Javascript
javascript 动态数据下的锚点错位问题解决方法
2008/12/24 Javascript
初学js 新节点的创建 删除 的步骤
2011/07/04 Javascript
Js实现当前点击a标签变色突出显示其他a标签回复原色
2013/11/27 Javascript
javascript将url中的参数加密解密代码
2014/11/17 Javascript
关于vue中的ajax请求和axios包问题
2018/04/19 Javascript
小程序外卖订单界面的示例代码
2019/12/30 Javascript
[05:05]给小松五分钟系列 第二期介绍为什么打DOTA2
2014/07/02 DOTA
python使用cookielib库示例分享
2014/03/03 Python
Python使用MONGODB入门实例
2015/05/11 Python
详解字典树Trie结构及其Python代码实现
2016/06/03 Python
Python AES加密实例解析
2018/01/18 Python
通过Turtle库在Python中绘制一个鼠年福鼠
2020/02/03 Python
Python爬虫爬取ts碎片视频+验证码登录功能
2021/02/22 Python
使用html5 canvas创建太空游戏的示例
2014/05/08 HTML / CSS
Bluebella法国官网:英国性感内衣品牌
2019/05/03 全球购物
大门门卫岗位职责
2013/11/30 职场文书
高分子材料与工程专业个人求职信
2013/12/15 职场文书
政法大学毕业生自荐信范文
2014/01/01 职场文书
幼儿园教师考核制度
2014/02/01 职场文书
小学中秋节活动方案
2014/02/06 职场文书
信息管理应届生求职信
2014/03/07 职场文书
教育英语专业毕业生的求职信
2014/03/13 职场文书
公务员保密承诺书
2014/03/27 职场文书
助学贷款贫困证明
2014/09/23 职场文书
员工辞职信怎么写
2015/02/27 职场文书
煤矿百日安全活动总结
2015/05/07 职场文书
2015年学校财务工作总结
2015/05/19 职场文书
拔河比赛新闻稿
2015/07/17 职场文书