pytorch构建多模型实例

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构建多模型实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • pytorch 求网络模型参数实例

    用pytorch训练一个神经网络时,我们通常会很关心模型的参数总量.下面分别介绍来两种方法求模型参数 一 .求得每一层的模型参数,然后自然的可以计算出总的参数. 1.先初始化一个网络模型model 比如我这里是 model=cliqueNet(里面是些初始化的参数) 2.调用model的Parameters类获取参数列表 一个典型的操作就是将参数列表传入优化器里.如下 optimizer = optim.Adam(model.parameters(), lr=opt.lr) 言归正传,继续回到参

  • pytorch 实现在预训练模型的 input上增减通道

    如何把imagenet预训练的模型,输入层的通道数随心所欲的修改,从而来适应自己的任务 #增加一个通道 w = layers[0].weight layers[0] = nn.Conv2d(4, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) layers[0].weight = torch.nn.Parameter(torch.cat((w, w[:, :1, :, :]), dim=1)) #方式2 w =

  • PyTorch使用cpu加载模型运算方式

    没gpu没cuda支持的时候加载模型到cpu上计算 将 model = torch.load(path, map_location=lambda storage, loc: storage.cuda(device)) 改为 model = torch.load(path, map_location='cpu') 然后删掉所有变量后面的.cuda()方法 以上这篇PyTorch使用cpu加载模型运算方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • pytorch构建网络模型的4种方法

    利用pytorch来构建网络模型有很多种方法,以下简单列出其中的四种. 假设构建一个网络模型如下: 卷积层-->Relu层-->池化层-->全连接层-->Relu层-->全连接层 首先导入几种方法用到的包: import torch import torch.nn.functional as F from collections import OrderedDict 第一种方法 # Method 1 --------------------------------------

  • Pytorch 保存模型生成图片方式

    三通道数组转成彩色图片 img=np.array(img1) img=img.reshape(3,img1.shape[2],img1.shape[3]) img=(img+0.5)*255##img做过归一化处理,[-0.5,0.5] img_path='/home/isee/wei/image/imageset/result.jpg' img=cv2.merge(img) cv2.imwrite(img_path,img) 单通道数组转化成灰度图 Img_mask=np.array(img_

  • pytorch构建多模型实例

    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 fro

  • pytorch 加载(.pth)格式的模型实例

    有一些非常流行的网络如 resnet.squeezenet.densenet等在pytorch里面都有,包括网络结构和训练好的模型. pytorch自带模型网址:https://pytorch-cn.readthedocs.io/zh/latest/torchvision/torchvision-models/ 按官网加载预训练好的模型: import torchvision.models as models # pretrained=True就可以使用预训练的模型 resnet18 = mod

  • pytorch: tensor类型的构建与相互转换实例

    Summary 主要包括以下三种途径: 使用独立的函数: 使用torch.type()函数: 使用type_as(tesnor)将张量转换为给定类型的张量. 使用独立函数 import torch tensor = torch.randn(3, 5) print(tensor) # torch.long() 将tensor投射为long类型 long_tensor = tensor.long() print(long_tensor) # torch.half()将tensor投射为半精度浮点类型

  • Pytorch之保存读取模型实例

    pytorch保存数据 pytorch保存数据的格式为.t7文件或者.pth文件,t7文件是沿用torch7中读取模型权重的方式.而pth文件是python中存储文件的常用格式.而在keras中则是使用.h5文件. # 保存模型示例代码 print('===> Saving models...') state = { 'state': model.state_dict(), 'epoch': epoch # 将epoch一并保存 } if not os.path.isdir('checkpoin

  • pytorch中获取模型input/output shape实例

    Pytorch官方目前无法像tensorflow, caffe那样直接给出shape信息,详见 https://github.com/pytorch/pytorch/pull/3043 以下代码算一种workaround.由于CNN, RNN等模块实现不一样,添加其他模块支持可能需要改代码. 例如RNN中bias是bool类型,其权重也不是存于weight属性中,不过我们只关注shape够用了. 该方法必须构造一个输入调用forward后(model(x)调用)才可获取shape #coding

  • Pytorch模型转onnx模型实例

    如下所示: import io import torch import torch.onnx from models.C3AEModel import PlainC3AENetCBAM device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def test(): model = PlainC3AENetCBAM() pthfile = r'/home/joy/Projects/

  • jenkins构建Docker 镜像实例详解

     jenkins构建Docker 镜像实例详解 前言:jenkins有Docker镜像,而之前我们说过使用jenkins打包Docker镜像,那么可否用jenkins的Docker镜像打包Docker镜像呢? 环境: CentOS 7     Docker 1.10.3 1.本机安装docker环境,并配置TCP访问接口 # vi /usr/lib/systemd/system/docker.service 修改ExecStart为: ExecStart=/usr/bin/docker daem

  • Queue 实现生产者消费者模型(实例讲解)

    Python中,队列是线程间最常用的交换数据的形式. Python Queue模块有三种队列及构造函数: 1.Python Queue模块的FIFO队列先进先出. class Queue.Queue(maxsize) 2.LIFO类似于堆,即先进后出. class Queue.LifoQueue(maxsize) 3.还有一种是优先级队列级别越低越先出来. class Queue.PriorityQueue(maxsize) 此包中的常用方法(q = Queue.Queue()): q.qsiz

  • PyTorch搭建多项式回归模型(三)

    PyTorch基础入门三:PyTorch搭建多项式回归模型 1)理论简介 对于一般的线性回归模型,由于该函数拟合出来的是一条直线,所以精度欠佳,我们可以考虑多项式回归来拟合更多的模型.所谓多项式回归,其本质也是线性回归.也就是说,我们采取的方法是,提高每个属性的次数来增加维度数.比如,请看下面这样的例子: 如果我们想要拟合方程: 对于输入变量和输出值,我们只需要增加其平方项.三次方项系数即可.所以,我们可以设置如下参数方程: 可以看到,上述方程与线性回归方程并没有本质区别.所以我们可以采用线性回

随机推荐