Files
2026-11-29 17:56:09 +01:00

57 lines
1.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_block(in_ch, out_ch):
"""2× (konvoluce 3×3 -> BatchNorm -> ReLU). Výška a šířka se nemění."""
return nn.Sequential(
nn.Conv2d(in_channels=in_ch, out_channels=out_ch, kernel_size=3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(),
nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU()
)
class MyModel(nn.Module):
def __init__(self, input_size=None, hidden_size=None, output_size=30, embedding_dim=128):
super().__init__()
self.e1 = conv_block(3, 32)
self.e2 = conv_block(32,64)
self.e3 = conv_block(64,128)
self.e4 = conv_block(128,256)
self.pool = nn.MaxPool2d(2)
self.classifier = nn.Linear(256, output_size)
self.embedder = nn.Linear(256, embedding_dim)
self.up = nn.Upsample(scale_factor=2)
self.d3 = conv_block(256+128, 128)
self.d2 = conv_block(128+64, 64)
self.d1 = conv_block(64+32,32)
self.mask_out = nn.Conv2d(32, 1, kernel_size=1)
def forward(self, x):
"""x [B, 3, 64, 64] -> (species [B, 30], masks [B, 1, 64, 64], embeddings [B, 128])"""
x = x * 2 - 1 # vstup 0..1 -> -1..1 (normalizace je v modelu, aby platila i u opravujícího)
f1 = self.e1(x)
f2 = self.e2(self.pool(f1))
f3 = self.e3(self.pool(f2))
f4 = self.e4(self.pool(f3))
v = f4.mean(dim=(2, 3))
species = self.classifier(v)
embeddings = F.normalize(self.embedder(v), dim=1)
d = self.d3(torch.cat([self.up(f4), f3], dim=1))
d = self.d2(torch.cat([self.up(d), f2], dim=1))
d = self.d1(torch.cat([self.up(d), f1], dim=1))
masks = self.mask_out(d)
return species, masks, embeddings
def get_embedding(self, x):
return self.forward(x)[2]