pytorch构建多模型实例
作者:朴素.无恙 发布时间:2021-05-14 13:30:00
标签: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)
'''
来源:https://blog.csdn.net/weixin_40123108/article/details/90670584


猜你喜欢
- filter的语法:filter(函数名字,可迭代的变量)其实filter就是一个“过滤器”:把【可迭代的变量】中的值,挨个地传给函数进行处
- 一、使用dotnet add package 命令行实现首先可以去这个网站:https://www.nuget.org/ 查找想要添加的引用
- Flask数据模型和连接数据库flask是基于MTV的结构,其中M指的就是模型,即数据模型,在项目中对应的是数据库。flask与数据库建立联
- 如下所示:def list_all_files(rootdir): import os _files = [] list = os.list
- Python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。Python提供
- 本文实例讲述了MySQL 事务概念与用法。分享给大家供大家参考,具体如下:事务的概念MySQL事务是一个或者多个的数据库操作,要么全部执行成
- 1.python函数运行原理import inspectframe = Nonedef foo(): bar()def bar(
- 下面给大家介绍如何利用pandas工具输出每行的索引值、及其对应的行数据,先给大家展示下输出结果,感兴趣的朋友可以参考具体实例代码。输出结果
- 目录distinctgroup byrow_number在使用SQL提数的时候,常会遇到表内有重复值的时候,比如我们想得到 uv (独立访客
- 本文实例讲述了微信小程序学习笔记之表单提交与PHP后台数据交互处理。分享给大家供大家参考,具体如下:前面一篇结介绍了微信小程序函数定义、页面
- Stickyworld 的网页应用已经支持视频拨放一段时间,但都是通过YouTube的嵌入模式实现。我们开始提供新的版本支持视频操作,可以让
- 一、MySQL数据库的实例管理器概述:1、MySQL数据库的实例管理器(IM)是通过TCP/IP端口运行的后台程序,用来监视和管理MySQL
- 一、方式一select * from student for updatestudent表需要操作人修改完commit之后才可以做其他的操作
- 示例下面是一个简单的Python爬虫Scrapy框架代码示例,该代码可以抓取百度搜索结果页面中指定关键字的链接和标题等信息:import s
- 目录一、async二、await:三、综合应用一、asyncasync创建一个异步函数来定义一个代码块,在其中运行异步代码;怎样变成异步函数
- 仿windows选项卡或叫做tabpan以及tabpage,现在还有最新的进展譬如仿淘宝网导航菜单效果皆属于此类:运行代码框<scri
- 8是典型的七段数码管的例子,因为刚好七段都有经过,这里我写的代码是从1开始右转。这是看Mooc视频写的一个关于用七段数码管显示当前时间# -
- 一、开始的话使用python简单的实现websocket服务器,可以在浏览器上实时显示远程服务器的日志信息。之前做了一个web版的发布系统,
- 本文实例讲述了Sanic框架蓝图用法。分享给大家供大家参考,具体如下:蓝图是可以用于应用程序内子路由的对象。蓝图并未向应用程序内添加路由,而
- 钉钉设置机器人首先在钉钉设置钉钉机器人群设置—> 智能群助手—>添加机器人—>自定义添加完成,得到一个Webhook AP