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)
            
        
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*</
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值