Python Unet网络结构网络结构pytorch简单实现简单实现+torchsummary可视化(可以直接可视化(可以直接
运行)运行)
Unet的网络结构:
根据该结构,用Pytorch实现Unet:
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torch.nn.functional as F
import numpy as np
import torch.utils.data as Data
seed = 2019
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.
import random
np.random.seed(seed) # Numpy module.
random.seed(seed) # Python random module.
torch.manual_seed(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
##定义卷积核
def default_conv(in_channels,out_channels,kernel_size,bias=True):
return nn.Conv2d(in_channels,out_channels,
kernel_size,padding=0,
bias=bias)
##定义ReLU
def default_relu():
return nn.ReLU(inplace=True)
class Up_Sample(nn.Module):
def __init__(self,in_channels,conv=default_conv,relu=default_relu):
super(Up_Sample,self).__init__()
up1 = nn.Upsample(scale_factor=2,mode='nearest')
up2 = conv(in_channels,in_channels//2,1)
self.module_up = nn.Sequential(up1,up2,relu())
def forward(self,input_down,input_left):
x = self.module_up(input_down)
dif = (input_left.shape[3] - x.shape[3])/2
input_left = input_left[:,:,int(dif):int(dif+x.shape[3]),int(dif):int(dif+x.shape[3])] return torch.cat((x,input_left),1)
评论2
最新资源