Files
efficient_surface_anomaly_d…/code/model.py
T

44 lines
1.8 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.
self.depthwise = nn.Conv2d(
in_channels=input_channels,
out_channels=input_channels,
kernel_size=kernel_size,
padding=kernel_size // 2,
groups=input_channels
)
self.relu = nn.ReLU()
self.batch_norm_depth = nn.BatchNorm2d(input_channels)
# Pointwise convolution (1x1 conv)
self.pointwise = nn.Conv2d(
in_channels=input_channels,
out_channels=output_channels_ds_conv,
kernel_size=1
)
self.batch_norm_point = nn.BatchNorm2d(output_channels_ds_conv)
# 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, 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
x = self.relu(self.depthwise(x))
x = self.batch_norm_depth(x)
x = self.relu(self.pointwise(x))
x = self.batch_norm_point(x)
x = self.global_avg_pool(x)
x = x.view(x.size(0), -1) # flatten (batch, channels)
x = self.relu(self.fc1(x))
x = self.dropout(x)
x = self.sigmoid(self.fc2(x))
return x