Files
efficient_surface_anomaly_d…/code/model.py
T
2025-04-08 09:43:56 +02:00

81 lines
2.9 KiB
Python

import torch.nn as nn
class ForeignObjectClassificationModel(nn.Module):
def __init__(self, input_channels, output_channels_ds_conv, 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,
kernel_size=1
)
self.batch_norm_point_1 = nn.BatchNorm2d(output_channels_ds_conv)
# DW2
kernel_size_2 = kernel_size
output_channels_ds_conv_2 = output_channels_ds_conv * 2
self.depthwise_2 = nn.Conv2d(
in_channels=output_channels_ds_conv,
out_channels=output_channels_ds_conv,
kernel_size=kernel_size_2,
#padding=kernel_size // 2,
groups=output_channels_ds_conv
)
self.batch_norm_depth_2 = nn.BatchNorm2d(output_channels_ds_conv)
# Pointwise convolution (1x1 conv)
self.pointwise_2 = nn.Conv2d(
in_channels=output_channels_ds_conv,
out_channels=output_channels_ds_conv_2,
kernel_size=1
)
self.batch_norm_point_2 = nn.BatchNorm2d(output_channels_ds_conv_2)
# 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_2, 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)
#DW 2
x = self.depthwise_2(x)
x = self.batch_norm_depth_2(x)
x = self.relu(x)
x = self.pointwise_2(x)
x = self.batch_norm_point_2(x)
x = self.relu(x)
#Pooling/Flattening
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