最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

pytorch構(gòu)建多模型實例

 更新時間:2020年01月15日 09:52:18   作者:樸素.無恙  
今天小編就為大家分享一篇pytorch構(gòu)建多模型實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

pytorch構(gòu)建雙模型

第一部分:構(gòu)建"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)

第二部分構(gòu)建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])#模型的結(jié)構(gòu)
#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])#模型的結(jié)構(gòu)
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])#模型的結(jié)構(gòu)
#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構(gòu)建多模型實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python實現(xiàn)隨機(jī)調(diào)用一個瀏覽器打開網(wǎng)頁

    python實現(xiàn)隨機(jī)調(diào)用一個瀏覽器打開網(wǎng)頁

    下面小編就為大家分享一篇python實現(xiàn)隨機(jī)調(diào)用一個瀏覽器打開網(wǎng)頁,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • python正則表達(dá)式對字符串的查找匹配

    python正則表達(dá)式對字符串的查找匹配

    正則表達(dá)式是一種文本模式,包括普通字符(例如,a 到 z 之間的字母)和特殊字符(稱為“元字符”),下面這篇文章主要給大家介紹了關(guān)于python正則表達(dá)式對字符串的查找匹配的相關(guān)資料,需要的朋友可以參考下
    2022-09-09
  • PyPy?如何讓Python代碼運(yùn)行得和C一樣快

    PyPy?如何讓Python代碼運(yùn)行得和C一樣快

    這篇文章主要介紹了如何讓Python代碼運(yùn)行得和C一樣快,由于?PyPy?只是?Python?的一種替代實現(xiàn),大多數(shù)時候它都是開箱即用,無需對?Python?項目進(jìn)行任何更改。它與?Web?框架?Django、科學(xué)計算包?Numpy?和許多其他包完全兼容,推薦大家多多使用
    2022-01-01
  • 基于Python快速處理PDF表格數(shù)據(jù)

    基于Python快速處理PDF表格數(shù)據(jù)

    這篇文章主要介紹了基于Python快速處理PDF表格數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-06-06
  • 使用Python實現(xiàn)簡單的學(xué)生成績管理系統(tǒng)

    使用Python實現(xiàn)簡單的學(xué)生成績管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了Python實現(xiàn)學(xué)生成績管理系統(tǒng),使用數(shù)據(jù)庫,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • python實現(xiàn)簡單聊天室功能 可以私聊

    python實現(xiàn)簡單聊天室功能 可以私聊

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)簡單聊天室功能,可以進(jìn)行私聊,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-07-07
  • Python+PyQT5實現(xiàn)手繪圖片生成器

    Python+PyQT5實現(xiàn)手繪圖片生成器

    這篇文章主要介紹了利用Python PyQT5制作一個手繪圖片生成器,可以將導(dǎo)入的彩色圖片通過python分析光源、灰度等操作生成手繪圖片。感興趣的可以跟隨小編一起了解一下
    2022-02-02
  • Python使用統(tǒng)計函數(shù)繪制簡單圖形實例代碼

    Python使用統(tǒng)計函數(shù)繪制簡單圖形實例代碼

    這篇文章主要給大家介紹了關(guān)于Python使用統(tǒng)計函數(shù)繪制簡單圖形的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • python 利用panda 實現(xiàn)列聯(lián)表(交叉表)

    python 利用panda 實現(xiàn)列聯(lián)表(交叉表)

    這篇文章主要介紹了python 利用panda 實現(xiàn)列聯(lián)表(交叉表),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Python中的datetime包與time包包和模塊詳情

    Python中的datetime包與time包包和模塊詳情

    這篇文章主要介紹了Python中的datetime包與datetime包和模塊詳情,文章圍繞主題展開詳細(xì)內(nèi)容,具有一的的參考價值,需要的小伙伴可以參考一下,希望對你有所幫助
    2022-02-02

最新評論

沁阳市| 丹阳市| 建水县| 兴义市| 抚宁县| 惠东县| 白朗县| 曲周县| 吉林省| 阳信县| 罗源县| 上思县| 恩施市| 盱眙县| 汪清县| 安庆市| 博客| 应用必备| 界首市| 桂东县| 石首市| 海宁市| 广宗县| 勐海县| 句容市| 吴旗县| 普宁市| 松原市| 敦煌市| 盈江县| 尤溪县| 伊宁县| 垫江县| 海城市| 贵定县| 盖州市| 弥渡县| 棋牌| 封丘县| SHOW| 安达市|