Files
efficient_surface_anomaly_d…/code/model2.py
T

149 lines
6.5 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 PatchClassifier(nn.Module):
"""
A small MLP that classifies each patch.
Each patch is first flattened from its [patch_H, patch_W] spatial dimensions into a feature vector.
In your assumed setting, the input already has shape [B, num_patches, patch_H, patch_W],
for example [10, 32, 32, 32] where the 32 channels represent 32 pre-divided patches.
This classifier outputs one scalar per patch.
"""
def __init__(self, in_features, hidden_units, dropout_rate):
super(PatchClassifier, self).__init__()
self.fc1 = nn.Linear(in_features, hidden_units)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(dropout_rate)
self.fc2 = nn.Linear(hidden_units, 1)
def forward(self, x):
# x shape: [B, num_patches, in_features]
x = self.fc1(x)
x = self.relu(x)
x = self.dropout(x)
x = self.fc2(x)
return x # Output shape: [B, num_patches, 1]
class PatchMerger(nn.Module):
def __init__(self, num_patches, merge_hidden_units, dropout_rate):
super(PatchMerger, self).__init__()
self.mlp = nn.Sequential(
nn.Linear(num_patches, merge_hidden_units),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(merge_hidden_units, 1)
)
def forward(self, x):
# x is expected to be [B, num_patches, 1]. For example, [10, 32, 1].
# Flatten it to [B, num_patches]:
x = x.view(x.size(0), -1)
out = self.mlp(x)
return torch.sigmoid(out) # Final output shape is [B, 1]
class ForeignObjectClassificationModel2(nn.Module):
def __init__(self,
input_channels, # Here, input_channels equals the number of patches (e.g., 32)
patch_size,
kernel_size,
num_conv_layers, # number of convolutional layers (operating on each patch independently)
patch_classifier_hidden_units, # hidden units for patch classifier MLP
dropout_rate_input,
dropout_rate_patch_classifier,
merge_hidden_units, # hidden units for patch merger MLP
dropout_rate_merge):
super(ForeignObjectClassificationModel2, self).__init__()
self.dropout_input = nn.Dropout(dropout_rate_input)
# Build convolutional blocks that process each patch independently.
conv_layers = []
for i in range(num_conv_layers):
padding = kernel_size // 2
# Here, we keep the number of channels constant since the channels represent individual patches.
conv_layers.append(DepthWiseSeperableConv(input_channels, input_channels, kernel_size, padding))
self.conv_layers = nn.Sequential(*conv_layers)
# Assume each patch is of size 32x32.
in_features_patch = patch_size * patch_size # e.g., 32*32 = 1024
# Patch classifier: processes each patch (flattened to a vector of length 1024).
self.patch_classifier = PatchClassifier(in_features=in_features_patch,
hidden_units=patch_classifier_hidden_units,
dropout_rate=dropout_rate_patch_classifier)
# Patch merger: aggregates the patch-level predictions with learnable parameters.
self.patch_merger = PatchMerger(input_channels, merge_hidden_units, dropout_rate_merge)
def forward(self, x):
# print(x.shape)
# x shape: [B, num_patches, patch_H, patch_W]
# e.g., [10, 32, 32, 32] -- 32 patches already provided as channels.
x = self.dropout_input(x)
# Apply convolutional layers.
# Note: The conv layers are applied per patch (channel) without mixing patch identities.
x = self.conv_layers(x) # Shape remains [B, num_patches, patch_H, patch_W].
# print(x.shape)
B, num_patches, H, W = x.shape # Here, num_patches should equal input_channels (e.g., 32)
# Flatten each patch's spatial dimensions.
patches = x.view(B, num_patches, -1) # shape: [B, num_patches, H*W]. With H=W=32, in_features = 1024.
# print(patches.shape)
# Apply the patch classifier to each patch.
patch_preds = self.patch_classifier(patches) # Expected shape: [B, num_patches, 1]
# print(patch_preds.shape)
# Merge patch predictions with the learnable PatchMerger.
final_preds = self.patch_merger(patch_preds) # shape: [B, 1]
# print(final_preds.shape)
return final_preds
# # Example usage:
# if __name__ == '__main__':
# # Assume the input is already divided into patches:
# # For a batch of 10 samples, we have 32 patches per sample, and each patch is 32x32.
# dummy_input = torch.randn(10, 32, 32, 32) # [B, num_patches, patch_H, patch_W]
# model = ForeignObjectClassificationModel2(
# patch_size=32,
# input_channels=32, # 32 patches provided (in the channel dimension)
# kernel_size=3,
# num_conv_layers=3, # Number of convolutional layers
# patch_classifier_hidden_units=64, # Hidden units in patch classifier MLP
# dropout_rate_input=0.5,
# dropout_rate_patch_classifier=0.5,
# merge_hidden_units=32, # Hidden units in patch merger MLP
# dropout_rate_merge=0.5
# )
# output = model(dummy_input)
# print("Output shape:", output.shape) # Expected: [10, 1]