unet网络python代码详解_使用pytorch实现论文中的unet网络

设计神经网络的一般步骤:

1. 设计框架

2. 设计骨干网络

Unet网络设计的步骤:

1. 设计Unet网络工厂模式

2. 设计编解码结构

3. 设计卷积模块

4. unet实例模块

Unet网络最重要的特征:

1. 编解码结构。

2. 解码结构,比FCN更加完善,采用连接方式。

3. 本质是一个框架,编码部分可以使用很多图像分类网络。

示例代码:

import torch

import torch.nn as nn

class Unet(nn.Module):

#初始化参数:Encoder,Decoder,bridge

#bridge默认值为无,如果有参数传入,则用该参数替换None

def __init__(self,Encoder,Decoder,bridge = None):

super(Unet,self).__init__()

self.encoder = Encoder(encoder_blocks)

self.decoder = Decoder(decoder_blocks)

self.bridge = bridge

def forward(self,x):

res = self.encoder(x)

out,skip = res[0],res[1,:]

if bridge is not None:

out = bridge(out)

out = self.decoder(out,skip)

return out

#设计编码模块

class Encoder(nn.Module):

def __init__(self,blocks):

super(Encoder,self).__init__()

#assert:断言函数,避免出现参数错误

assert len(blocks) > 0

#nn.Modulelist():模型列表,所有的参数可以纳入网络,但是没有forward函数

self.blocks = nn.Modulelist(blocks)

def forward(self,x):

skip = []

for i in range(len(self.blocks) - 1):

x = self.blocks[i](x)

skip.append(x)

res = [self.block[i+1](x)]

#列表之间可以通过+号拼接

res += skip

return res

#设计Decoder模块

class Decoder(nn.Module):

def __init__(self,blocks):

super(Decoder, self).__init__()

assert len(blocks) > 0

self.blocks = nn.Modulelist(blocks)

def ceter_crop(self,skips,x):

_,_,height1,width1 = skips.shape()

_,_,height2,width2 = x.shape()

#对图像进行剪切处理,拼接的时候保持对应size参数一致

ht,wt = min(height1,height2),min(width1,width2)

dh1 = (height1 - height2)//2 if height1 > height2 else 0

dw1 = (width1 - width2)//2 if width1 > width2 else 0

dh2 = (height2 - height1)//2 if height2 > height1 else 0

dw2 = (width2 - width1)//2 if width2 > width1 else 0

return skips[:,:,dh1:(dh1 + ht),dw1:(dw1 + wt)],\

x[:,:,dh2:(dh2 &#

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值