Files
efficient_surface_anomaly_d…/code/model.py
T

126 lines
4.7 KiB
Python

import torch
import torch.nn as nn
import torch.nn.functional as F
class RandomChannelShuffle(nn.Module):
def forward(self, x):
# x shape: (batch, channels, height, width)
perm = torch.randperm(x.size(1), device=x.device)
return x[:, perm, ...]
class RandomChannelRotation(nn.Module):
def __init__(self):
super(RandomChannelRotation, self).__init__()
# There are 4 possible rotations: 0, 90, 180, and 270 degrees.
# We'll sample a random integer in [0, 3] as the number of 90° rotations.
def forward(self, x):
# x shape: (batch, channels, height, width)
B, C, H, W = x.size()
# Create an empty tensor for the output.
out = torch.empty_like(x)
# Generate a random rotation for each channel in each example.
# This produces a tensor of shape (B, C) with values in {0, 1, 2, 3}.
ks = torch.randint(0, 4, (B, C), device=x.device)
for b in range(B):
for c in range(C):
# For each channel, apply the corresponding rotation.
out[b, c] = torch.rot90(x[b, c], k=ks[b, c].item(), dims=(0, 1))
return out
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,
conv_out_channels,
kernel_size,
num_conv_layers, # number of convolutional layers
num_fc_layers, # number of hidden FC layers before final output
hidden_units, # number of units per hidden FC layer
dropout_rate,
with_shuffle_channels,
with_rotate_channels):
super(ForeignObjectClassificationModel, self).__init__()
# Optionally apply channel shuffling.
self.with_shuffle_channels = with_shuffle_channels
if self.with_shuffle_channels:
self.shuffle_channels = RandomChannelShuffle()
# Optionally apply channel rotation.
self.with_rotate_channels = with_rotate_channels
if self.with_rotate_channels:
self.rotate_channels = RandomChannelRotation()
# Input dropout.
self.dropout = nn.Dropout(dropout_rate)
# Build a list of convolutional blocks.
conv_layers = []
for i in range(num_conv_layers):
in_ch = input_channels if i == 0 else conv_out_channels
padding = kernel_size // 2
conv_layers.append(DepthWiseSeperableConv(in_ch, conv_out_channels, kernel_size, padding))
self.dws_conv_layers = nn.Sequential(*conv_layers)
# Global average pooling to reduce spatial dimensions.
self.global_avg_pool = nn.AdaptiveAvgPool2d(1)
# Build the fully connected classification head.
fc_layers = []
fc_input_dim = conv_out_channels # from 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.
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):
if self.training:
# Optionally shuffle channels.
if self.with_shuffle_channels:
x = self.shuffle_channels(x)
# Optionally rotate channels.
if self.with_rotate_channels:
x = self.rotate_channels(x)
x = self.dropout(x)
x = self.dws_conv_layers(x)
x = self.global_avg_pool(x)
x = x.view(x.size(0), -1) # flatten (batch, channels)
x = self.binary_cls_head(x)
return x