Files
efficient_surface_anomaly_d…/code/model.py
T
2025-04-08 18:39:01 +02:00

52 lines
1.9 KiB
Python

import torch.nn as nn
class ForeignObjectClassificationModel(nn.Module):
def __init__(self, input_channels, output_channels_ds_conv_1, kernel_size, hidden_units, dropout_rate):
super(ForeignObjectClassificationModel, self).__init__()
# Depthwise convolution: set groups=input_channels so that each channel is convolved separately.
# DW1
self.depthwise_1 = nn.Conv2d(
in_channels=input_channels,
out_channels=input_channels,
kernel_size=kernel_size,
padding=kernel_size // 2,
groups=input_channels
)
self.batch_norm_depth_1 = nn.BatchNorm2d(input_channels)
self.relu = nn.ReLU()
# Pointwise convolution (1x1 conv)
self.pointwise_1 = nn.Conv2d(
in_channels=input_channels,
out_channels=output_channels_ds_conv_1,
kernel_size=1
)
self.batch_norm_point_1 = nn.BatchNorm2d(output_channels_ds_conv_1)
# Global average pooling to output (batch, channels, 1, 1)
self.global_avg_pool = nn.AdaptiveAvgPool2d(1)
# Fully connected layers
self.fc1 = nn.Linear(output_channels_ds_conv_1, hidden_units)
self.dropout = nn.Dropout(dropout_rate)
self.fc2 = nn.Linear(hidden_units, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
# Originial Mobile-Net uses Depthwise-Separable Convolution based on:
# 3x3 Depthwise Conv, bn, relu, 1x1 Conv (pointwise), bn, relu
#DW 1
x = self.depthwise_1(x)
x = self.batch_norm_depth_1(x)
x = self.relu(x)
x = self.pointwise_1(x)
x = self.batch_norm_point_1(x)
x = self.relu(x)
x = self.global_avg_pool(x)
x = x.view(x.size(0), -1) # flatten (batch, channels)
#CLS-Head
x = self.fc1(x)
x = self.relu(x)
x = self.dropout(x)
x = self.fc2(x)
x = self.sigmoid(x)
return x