Files
2025-04-18 21:21:33 +02:00

90 lines
3.0 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
# ------------------------------------------------------------------
class ColumnFeatureExtractor(nn.Module):
"""
(B,1,H,W) → (B,W,5) with statistics
mean /255 , std /255 , min /255 , max /255 , range /255
"""
def __init__(self):
super().__init__()
self.out_dim = 5
self.scale = 255.0
def forward(self, x):
mean = x.mean(dim=2) / self.scale
std = x.std (dim=2, unbiased=False) / self.scale
minv = x.min(dim=2).values / self.scale
maxv = x.max(dim=2).values / self.scale
rng = maxv - minv # already /255
feat = torch.cat([mean, std, minv, maxv, rng], 1) # (B,5,W)
return feat.permute(0, 2, 1) # (B,W,5)
# ------------------------------------------------------------------
class ImageSequenceClassifier(nn.Module):
"""gray → column stats → 1‑direction GRU/LSTM → sigmoid"""
GRAY_W = torch.tensor([0.2989, 0.5870, 0.1140]).view(1, 3, 1, 1)
def __init__(self,
rnn_hidden: int = 128,
rnn_type: str = "GRU", # "GRU" or "LSTM"
cls_hidden: int = 128,
dropout: float = 0.1):
super().__init__()
self.register_buffer("gray_w", self.GRAY_W)
self.fe = ColumnFeatureExtractor() # out_dim = 5
rnn_cls = nn.GRU if rnn_type.upper() == "GRU" else nn.LSTM
self.rnn = rnn_cls(input_size=self.fe.out_dim,
hidden_size=rnn_hidden,
batch_first=True) # single, uni‑direction layer
self.head = nn.Sequential(
nn.Linear(rnn_hidden, cls_hidden),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(cls_hidden, 1),
nn.Sigmoid()
)
# ----------------------------------------------------------
def rgb2gray(self, x):
if x.shape[1] == 3:
x = (x * self.GRAY_W.to(x)).sum(1, keepdim=True)
return x
# ----------------------------------------------------------
def forward(self, x):
x = self.rgb2gray(x) # (B,1,H,W)
seq = self.fe(x) # (B,W,5)
seq_out, h = self.rnn(seq) # h: (1, B, hidden) for both GRU & LSTM
if isinstance(h, tuple): # LSTM returns (h_n, c_n)
h = h[0]
last = h.squeeze(0) # (B, hidden)
return self.head(last) # (B,1)
# ------------------------------------------------------------------
def main():
torch.manual_seed(0)
B, H, W = 2, 128, 128
imgs = torch.rand(B, 3, H, W) * 255 # simulate 0‑255 input
model = ImageSequenceClassifier(rnn_hidden=64,
cls_hidden=32,
dropout=0.2,
rnn_type="LSTM")
model.eval()
with torch.no_grad():
print("sigmoid outputs:", model(imgs).squeeze())
if __name__ == "__main__":
main()