model
unknown
python
a year ago
2.1 kB
6
Indexable
import torch
import torch.nn as nn
import torch.nn.functional as F
class CNN3D(nn.Module):
"""3D Convolutional Neural Network"""
def __init__(self, width=128, height=128, depth=64):
super(CNN3D, self).__init__()
# 第一层卷积
self.conv1 = nn.Conv3d(in_channels=1, out_channels=64, kernel_size=3, padding=1) # padding=1 保持 shape
self.pool1 = nn.MaxPool3d(kernel_size=2)
self.bn1 = nn.BatchNorm3d(64)
# 第二层卷积
self.conv2 = nn.Conv3d(in_channels=64, out_channels=64, kernel_size=3, padding=1)
self.pool2 = nn.MaxPool3d(kernel_size=2)
self.bn2 = nn.BatchNorm3d(64)
# 第三层卷积
self.conv3 = nn.Conv3d(in_channels=64, out_channels=128, kernel_size=3, padding=1)
self.pool3 = nn.MaxPool3d(kernel_size=2)
self.bn3 = nn.BatchNorm3d(128)
# 第四层卷积
self.conv4 = nn.Conv3d(in_channels=128, out_channels=256, kernel_size=3, padding=1)
self.pool4 = nn.MaxPool3d(kernel_size=2)
self.bn4 = nn.BatchNorm3d(256)
# 全局平均池化
self.global_avg_pool = nn.AdaptiveAvgPool3d(output_size=1)
# 全连接层
self.fc1 = nn.Linear(256, 512) # 输入通道数与前一层输出一致
self.dropout = nn.Dropout(0.3)
self.fc2 = nn.Linear(512, 1) # 二分类输出
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool1(x)
x = self.bn1(x)
x = F.relu(self.conv2(x))
x = self.pool2(x)
x = self.bn2(x)
x = F.relu(self.conv3(x))
x = self.pool3(x)
x = self.bn3(x)
x = F.relu(self.conv4(x))
x = self.pool4(x)
x = self.bn4(x)
x = self.global_avg_pool(x) # (batch_size, 256, 1, 1, 1)
x = torch.flatten(x, start_dim=1) # 展平成 (batch_size, 256)
x = F.relu(self.fc1(x))
x = self.dropout(x)
x = torch.sigmoid(self.fc2(x)) # 输出 sigmoid 概率
return x
Editor is loading...
Leave a Comment