This commit is contained in:
zase414 committed 2026-11-27 16:47:43 +01:00
1 parent c870ec0961
commit 368aa71658
7 files changed
+328 -99

No files matched your search

+68 -36
View File
@@ -1,51 +1,83 @@
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
class MyModel(torch.nn.Module):
"""
MyModel is a custom neural network model for image classification and segmentation and vectorization.
"""
def conv_block(in_ch, out_ch):
"""Two 3x3 convolutions, each followed by BatchNorm and ReLU.
Keeps the spatial size (padding=1), changes the number of channels."""
return nn.Sequential(
nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
def __init__(self, input_size, hidden_size, output_size=30):
"""Initialize the model.
Args:
input_size (int): Size of the input features.
hidden_size (int): Size of the hidden layers.
output_size (int): Size of the output layer (number of classes).
"""
super(MyModel, self).__init__()
self.backbone = # ‼️‼️‼️‼️ Define your backbone ‼️‼️‼️‼️
class MyModel(nn.Module):
def __init__(self, input_size=None, hidden_size=128, output_size=30, embedding_dim=128):
# input_size / hidden_size are passed by train.py but a CNN does not need them
super().__init__()
self.species_classifier = # ‼️‼️‼️‼️ Define you classifier ‼️‼️‼️‼️
# ---------- backbone (encoder): 64x64 -> 8x8, 3 -> 256 channels ----------
self.enc1 = conv_block(3, 32) # [B, 32, 64, 64]
self.enc2 = conv_block(32, 64) # [B, 64, 32, 32]
self.enc3 = conv_block(64, 128) # [B, 128, 16, 16]
self.enc4 = conv_block(128, 256) # [B, 256, 8, 8]
self.pool = nn.MaxPool2d(2) # halves H and W
self.segmentation_head = # ‼️‼️‼️‼️ Define your segmentation head ‼️‼️‼️‼️
# ---------- classification head: 256 numbers -> 30 class scores ----------
self.species_classifier = nn.Sequential(
nn.Dropout(0.3),
nn.Linear(256, output_size),
)
# ---------- embedding head: 256 numbers -> embedding_dim numbers ----------
self.embedding_head = nn.Sequential(
nn.Linear(256, 256),
nn.ReLU(inplace=True),
nn.Linear(256, embedding_dim),
)
# ---------- segmentation head (decoder): 8x8 -> 64x64, 1 channel ----------
self.up = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
self.dec3 = conv_block(256 + 128, 128) # 16x16
self.dec2 = conv_block(128 + 64, 64) # 32x32
self.dec1 = conv_block(64 + 32, 32) # 64x64
self.mask_out = nn.Conv2d(32, 1, kernel_size=1)
def encode(self, x):
f1 = self.enc1(x) # [B, 32, 64, 64]
f2 = self.enc2(self.pool(f1)) # [B, 64, 32, 32]
f3 = self.enc3(self.pool(f2)) # [B, 128, 16, 16]
f4 = self.enc4(self.pool(f3)) # [B, 256, 8, 8]
return f1, f2, f3, f4
def embed(self, f4):
pooled = f4.mean(dim=(2, 3)) # [B, 256] global average pool
emb = self.embedding_head(pooled) # [B, D]
return F.normalize(emb, dim=1) # length 1 -> cosine friendly
def forward(self, x):
"""Forward pass for the model.
f1, f2, f3, f4 = self.encode(x)
Args:
x (torch.Tensor): Input tensor.
# classification
pooled = f4.mean(dim=(2, 3)) # [B, 256]
species = self.species_classifier(pooled) # [B, 30] (logits)
# embedding
embeddings = self.embed(f4) # [B, D]
# segmentation: upsample, glue on the encoder feature of the same size, convolve
d = self.dec3(torch.cat([self.up(f4), f3], dim=1)) # [B, 128, 16, 16]
d = self.dec2(torch.cat([self.up(d), f2], dim=1)) # [B, 64, 32, 32]
d = self.dec1(torch.cat([self.up(d), f1], dim=1)) # [B, 32, 64, 64]
masks = self.mask_out(d) # [B, 1, 64, 64] (logits)
Returns:
tuple: (species, masks, embeddings)
species (torch.Tensor): The species classification logits.
masks (torch.Tensor): The segmentation masks.
embeddings (torch.Tensor): The feature embeddings.
"""
# ‼️‼️‼️‼️ Define the forward pass ‼️‼️‼️‼️
return species, masks, embeddings
def get_embedding(self, x):
"""Get the feature embeddings from the model.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: The feature embeddings.
"""
# ‼️‼️‼️‼️ Implement the embedding extraction ‼️‼️‼️‼️
return embeddings
*_, f4 = self.encode(x)
return self.embed(f4)