Files

111 lines
4.8 KiB
Python

import torch
import torch.nn as nn
import torch.nn.functional as F
class DepthWiseSeperableConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, padding):
super(DepthWiseSeperableConv, self).__init__()
# Depthwise convolution (each channel is convolved separately)
self.depthwise = nn.Conv2d(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=kernel_size,
padding=padding,
groups=in_channels
)
self.batch_norm_depth = nn.BatchNorm2d(in_channels)
self.relu = nn.ReLU()
# Pointwise convolution (mixes the channels)
self.pointwise = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1
)
self.batch_norm_pointwise = nn.BatchNorm2d(out_channels)
def forward(self, x):
x = self.depthwise(x)
x = self.batch_norm_depth(x)
x = self.relu(x)
x = self.pointwise(x)
x = self.batch_norm_pointwise(x)
x = self.relu(x)
return x
class ForeignObjectClassificationModel(nn.Module):
def __init__(self,
input_channels,
base_conv_channels, # initial channels for first DS conv
kernel_size,
num_conv_layers, # number of convolutional blocks
num_fc_layers, # number of hidden FC layers before final output
hidden_units, # number of units per hidden FC layer
pooling_after_each_conv, # whether to apply pooling after each conv block
conv_pooling_type, # pooling type after conv block: 'max' or 'avg'
global_pooling_type # global pooling type before FC head: 'max' or 'avg'
):
super(ForeignObjectClassificationModel, self).__init__()
self.pooling_after_each_conv = pooling_after_each_conv
self.conv_pooling_type = conv_pooling_type
# Build the convolutional blocks as a sequential container.
conv_layers = []
if base_conv_channels == "double_input":
base_conv_channels = input_channels * 2
current_channels = base_conv_channels # Starting number of output channels.
in_ch = input_channels
for i in range(num_conv_layers):
padding = kernel_size // 2
# Add the DS convolution block.
conv_layers.append(DepthWiseSeperableConv(in_ch, current_channels, kernel_size, padding))
# Optionally add a pooling layer after each block to reduce spatial dimensions.
if pooling_after_each_conv:
if conv_pooling_type == 'max':
conv_layers.append(nn.MaxPool2d(kernel_size=2, stride=2))
elif conv_pooling_type == 'avg':
conv_layers.append(nn.AvgPool2d(kernel_size=2, stride=2))
else:
raise ValueError("Unsupported pooling type: {}".format(conv_pooling_type))
# Prepare for the next block: update the input channel to the current block's output,
# and optionally double the number of channels.
in_ch = current_channels
if base_conv_channels == "double_input":
current_channels *= 2 # Double the number of channels for the next block.
# Assign the built list to an nn.Sequential, which will pass data through the layers in order.
self.conv_layers = nn.Sequential(*conv_layers)
# Global pooling before the fully connected head: aggregates the spatial dimensions.
if global_pooling_type == 'avg':
self.global_pool = nn.AdaptiveAvgPool2d(1)
elif global_pooling_type == 'max':
self.global_pool = nn.AdaptiveMaxPool2d(1)
else:
raise ValueError("Unsupported global pooling type: {}".format(global_pooling_type))
# The number of channels output by the last DS conv block is the last value assigned to in_ch.
final_channels = in_ch
# Build the fully connected classification head.
fc_layers = []
fc_input_dim = final_channels # From the pooling output.
for i in range(num_fc_layers):
fc_layers.append(nn.Linear(fc_input_dim, hidden_units))
fc_layers.append(nn.ReLU())
fc_input_dim = hidden_units
# Final classification layer producing one output (binary classification) with sigmoid activation.
fc_layers.append(nn.Linear(fc_input_dim, 1))
fc_layers.append(nn.Sigmoid())
self.binary_cls_head = nn.Sequential(*fc_layers)
def forward(self, x):
x = self.conv_layers(x)
x = self.global_pool(x)
x = x.view(x.size(0), -1) # Flatten (batch, channels)
x = self.binary_cls_head(x)
return x