引言
本篇文章主要内容为对应Pytorch中的示例代码编写MONAI代码以实现相同目的。所以本文概念性知识不再赘述,主要为代码复现。

相关知识简述
因为MONAI是基于Pytorch的,所以可以直接用torch.nn.Module作为父类进行继承。MONAI封装了很多模型层和网络模型,不过鉴于我们要做的是复现Pytorch的自定义网络,所以只用其中的模型层即可。自定义网络的步骤与Pytorch一摸一样(毕竟就是Pytorch框架),实现__init__和forward两个方法即可,接下来进行模型搭建。
模型搭建
导入所需的包,模型层上为卷积,上采样,最大池化,激活函数
python
import torch
import torch.nn as nn
from monai.networks.blocks import Convolution, UpSample
网络定义与搭建
python
class MONAIStyleSegNet(nn.Module):
"""使用 MONAI 组件的分割网络"""
def __init__(self, in_channels=3, out_channels=1):
super().__init__()
# 编码器(使用 MONAI 的 Convolution 块)
self.enc1 = Convolution(
spatial_dims=2,
in_channels=in_channels, # 输入通道
out_channels=64, #输出通道
kernel_size=3, #卷积核宽度
strides=1, #步长
padding=1, #padding
act='RELU', #激活函数
norm=None,
)
self.pool1 = nn.MaxPool2d(2) #最大池化
self.enc2 = Convolution(
spatial_dims=2,
in_channels=64,
out_channels=128,
kernel_size=3,
strides=1, # ← 改为 strides
padding=1,
act='RELU',
norm=None,
)
self.pool2 = nn.MaxPool2d(2)
self.enc3 = Convolution(
spatial_dims=2,
in_channels=128,
out_channels=256,
kernel_size=3,
strides=1, # ← 改为 strides
padding=1,
act='RELU',
norm=None,
)
self.pool3 = nn.MaxPool2d(2)
# 解码器
self.up1 = UpSample(
spatial_dims=2,
in_channels=256,
out_channels=128,
scale_factor=2,
mode='deconv',
)
self.dec1 = Convolution(
spatial_dims=2,
in_channels=128,
out_channels=64,
kernel_size=3,
strides=1,
padding=1,
act='RELU',
norm=None,
)
self.up2 = UpSample(
spatial_dims=2,
in_channels=64,
out_channels=64,
scale_factor=2,
mode='deconv',
)
self.dec2 = Convolution(
spatial_dims=2,
in_channels=64,
out_channels=32,
kernel_size=3,
strides=1,
padding=1,
act='RELU',
norm=None,
)
self.up3 = UpSample(
spatial_dims=2,
in_channels=32,
out_channels=32,
scale_factor=2,
mode='deconv',
)
self.dec3 = Convolution(
spatial_dims=2,
in_channels=32,
out_channels=out_channels,
kernel_size=1,
strides=1,
padding=0,
act=None,
norm=None,
)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
# 编码
x = self.enc1(x)
x = self.pool1(x)
x = self.enc2(x)
x = self.pool2(x)
x = self.enc3(x)
x = self.pool3(x)
# 解码
x = self.up1(x)
x = self.dec1(x)
x = self.up2(x)
x = self.dec2(x)
x = self.up3(x)
x = self.dec3(x)
x = self.sigmoid(x)
return x
参数获取与尺寸验证
获取网络结构
python
model = MONAIStyleSegNet(in_channels=3, out_channels=1)
for i in model.named_parameters():
print(i[0],i[1].size())
获取总参数量
python
total_params = sum(p.numel() for p in model.parameters())
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"总参数量: {total_params:,}")
print(f"可训练参数量: {trainable_params:,}")
测试输出尺寸
python
# 测试
model = MONAIStyleSegNet(in_channels=3, out_channels=1)
x = torch.randn(1, 3, 512, 512)
output = model(x)
print(f"MONAI 网络输出: {output.shape}")
python
MONAI 风格网络输出: torch.Size([1, 1, 512, 512])
结尾及相关链接
欧克,MONAI网络也搭建好了。我们下期再聊ദ്ദി (⩌ᴗ⩌ )
相关链接:
示例数据集:
MONAI官网:
Pytorch官网:
对应的Pytorch文章: