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)
class Unet(nn.Module):
def __init__(self,in_channels,out_channels,conv=default_conv,relu=default_relu,n_feats=64):
super(Unet,self).__init__()
left1 = [conv(in_channels,n_feats,3),relu(),conv(n_feats,n_feats,3)]
left2 = [conv(n_feats,2*n_feats,3),relu(),conv(2*n_feats,2*n_feats,3)]
left3 = [conv(2*n_feats,4*n_feats,3),relu(),conv(4*n_feats,4*</