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使用shelve模块实现简单数据存储的方法
May 20 Python
在Python中用get()方法获取字典键值的教程
May 21 Python
Python中实现变量赋值传递时的引用和拷贝方法
Apr 29 Python
详解python里的命名规范
Jul 16 Python
利用Python如何批量修改数据库执行Sql文件
Jul 29 Python
django从请求到响应的过程深入讲解
Aug 01 Python
Python告诉你木马程序的键盘记录原理
Feb 02 Python
python 自动轨迹绘制的实例代码
Jul 05 Python
利用Python进行图像的加法,图像混合(附代码)
Jul 14 Python
windows上彻底删除jupyter notebook的实现
Apr 13 Python
python中Array和DataFrame相互转换的实例讲解
Feb 03 Python
解决pytorch 的state_dict()拷贝问题
Mar 03 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
php 高性能书写
2010/12/11 PHP
sae使用smarty模板的方法
2013/12/17 PHP
zen cart实现订单中增加paypal中预留电话的方法
2016/07/12 PHP
使用php完成常见的文件上传功能(推荐)
2017/01/13 PHP
php将从数据库中获得的数据转换成json格式并输出的方法
2018/08/21 PHP
Javascript 获取链接(url)参数的方法[正则与截取字符串]
2010/02/09 Javascript
javascript css styleFloat和cssFloat
2010/03/15 Javascript
JQuery文本框高亮显示插件代码
2011/04/02 Javascript
跨域请求的完美解决方法(JSONP, CORS)
2016/06/12 Javascript
nodejs对express中next函数的一些理解
2017/09/08 NodeJs
vue.js todolist实现代码
2017/10/29 Javascript
windows系统下更新nodejs版本的方案
2017/11/24 NodeJs
Vue filter格式化时间戳时间成标准日期格式的方法
2018/09/16 Javascript
详解element-ui中表单验证的三种方式
2019/09/18 Javascript
js实现列表向上无限滚动
2020/01/13 Javascript
easyUI使用分页过滤器对数据进行分页操作实例分析
2020/06/01 Javascript
[42:24]完美世界DOTA2联赛循环赛 LBZS vs DM BO2第一场 11.01
2020/11/02 DOTA
Python对两个有序列表进行合并和排序的例子
2014/06/13 Python
利用python实现xml与数据库读取转换的方法
2017/06/17 Python
在python2.7中用numpy.reshape 对图像进行切割的方法
2018/12/05 Python
对python 操作solr索引数据的实例详解
2018/12/07 Python
Python线程之定位与销毁的实现
2019/02/17 Python
PyQt5 实现给窗口设置背景图片的方法
2019/06/13 Python
Django model 中设置联合约束和联合索引的方法
2019/08/06 Python
Python 异步协程函数原理及实例详解
2019/11/13 Python
用Python画小女孩放风筝的示例
2019/11/23 Python
windows环境中利用celery实现简单任务队列过程解析
2019/11/29 Python
Python爬虫自动化获取华图和粉笔网站的错题(推荐)
2021/01/08 Python
Optimalprint加拿大:在线打印服务
2020/04/03 全球购物
经济实惠的名牌太阳镜和眼镜:Privé Revaux
2021/02/07 全球购物
房地产促销活动方案
2014/03/01 职场文书
2016年党建工作简报
2015/11/26 职场文书
2019通用版导游词范本!
2019/08/07 职场文书
python tqdm用法及实例详解
2021/06/16 Python
Java设计模式之代理模式
2022/04/22 Java/Android
Elasticsearch6.2服务器升配后的bug(避坑指南)
2022/09/23 Servers