Added sequential analysis model
This commit is contained in:
+21
-9
@@ -8,6 +8,8 @@ from torch.utils.data import DataLoader, TensorDataset
|
||||
from data_adapter import pad_image_and_resize
|
||||
from model4 import ForeignObjectClassificationModel
|
||||
import random
|
||||
import gc
|
||||
|
||||
|
||||
# --- GPU Setup ---
|
||||
device = "cuda"
|
||||
@@ -207,7 +209,8 @@ class ExperimentPipeline:
|
||||
batch_size,
|
||||
model_save_path,
|
||||
log_path,
|
||||
configuration_name):
|
||||
configuration_name,
|
||||
patience):
|
||||
|
||||
print(f"\n▶ {configuration_name} "
|
||||
f"| ks={kernel_size} | layers={num_conv_layers} | tiles={num_tiles_per_side}×{num_tiles_per_side} "
|
||||
@@ -236,7 +239,7 @@ class ExperimentPipeline:
|
||||
# ─── train / validate ─────────────────────────────────────
|
||||
best_val_acc, model = train_and_validate(model, optimizer, criterion,
|
||||
train_loader, val_loader,
|
||||
epochs, patience=50,
|
||||
epochs, patience=patience,
|
||||
device=self.device,
|
||||
num_tiles=num_tiles)
|
||||
print(f" best‑val‑acc = {best_val_acc:.4f}")
|
||||
@@ -297,15 +300,19 @@ def main():
|
||||
#TODO: if that works somehow, than sequence classifier
|
||||
|
||||
epochs = 1000
|
||||
batch_size = 128
|
||||
pooling_after_each_conv_list = [False]
|
||||
conv_pooling_type_list = ["max"] #Not used
|
||||
patience = 50
|
||||
batch_size = 512
|
||||
pooling_after_each_conv_list = [True]
|
||||
#TODO: Verkleinern scheint ja gut zu klappen
|
||||
#TODO: Naja statt DSConv, einfach die statistischen Features extrahieren
|
||||
#TODO weniger Daten?
|
||||
conv_pooling_type_list = ["max"]
|
||||
global_pooling_type_list = ["avg"]
|
||||
learning_rates = [0.001]
|
||||
target_image_sizes = [394]
|
||||
n_tiles_per_side_list = [16, 8, 4, 2]
|
||||
kernel_sizes = [3, 5, 7, 9]
|
||||
num_conv_layers_list = [3, 2, 1]
|
||||
n_tiles_per_side_list = [16] #, 32, 16, 8, 4]
|
||||
kernel_sizes = [3]
|
||||
num_conv_layers_list = [4]#, 3, 2, 1]
|
||||
|
||||
# ────────────────────────────────────────────────────────────────
|
||||
for lr in learning_rates:
|
||||
@@ -349,10 +356,15 @@ def main():
|
||||
batch_size = batch_size,
|
||||
model_save_path = model_save_path,
|
||||
log_path = log_path,
|
||||
configuration_name = cfg_name)
|
||||
configuration_name = cfg_name,
|
||||
patience = patience)
|
||||
|
||||
with open(checkpoint_file, "a") as f:
|
||||
f.write(cfg_name + "\n")
|
||||
reset_random_seeds(mySeed)
|
||||
gc.collect()
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
import os
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.optim as optim
|
||||
from PIL import Image
|
||||
from torch.utils.data import DataLoader, TensorDataset
|
||||
from data_adapter import pad_image_and_resize
|
||||
from model5 import ImageSequenceClassifier
|
||||
import random
|
||||
import gc
|
||||
|
||||
|
||||
# --- GPU Setup ---
|
||||
device = "cuda"
|
||||
|
||||
# -------------------------------
|
||||
def get_data_from_path(path):
|
||||
ok_path = os.path.join(path, "ok")
|
||||
nok_path = os.path.join(path, "nok")
|
||||
|
||||
# Check if 'ok' folder exists.
|
||||
if os.path.exists(ok_path):
|
||||
ok_files = [os.path.join(ok_path, f) for f in os.listdir(ok_path)]
|
||||
ok_labels = [0] * len(ok_files)
|
||||
else:
|
||||
ok_files = []
|
||||
ok_labels = []
|
||||
|
||||
# Check if 'nok' folder exists.
|
||||
if os.path.exists(nok_path):
|
||||
nok_files = [os.path.join(nok_path, f) for f in os.listdir(nok_path)]
|
||||
nok_labels = [1] * len(nok_files)
|
||||
else:
|
||||
nok_files = []
|
||||
nok_labels = []
|
||||
|
||||
return ok_files + nok_files, ok_labels + nok_labels
|
||||
|
||||
# -------------------------------
|
||||
def get_test_datasets_from_path(test_folder_path):
|
||||
"""
|
||||
Scans the test folder for subfolders.
|
||||
Each subfolder should contain an 'ok' and/or 'nok' directory.
|
||||
Returns a dictionary mapping subfolder name to (files, labels).
|
||||
"""
|
||||
test_datasets = {}
|
||||
for subfolder in os.listdir(test_folder_path):
|
||||
subfolder_path = os.path.join(test_folder_path, subfolder)
|
||||
if os.path.isdir(subfolder_path):
|
||||
files, labels = get_data_from_path(subfolder_path)
|
||||
test_datasets[subfolder] = (files, labels)
|
||||
return test_datasets
|
||||
|
||||
def load_dataset(files, labels, target_image_size):
|
||||
"""
|
||||
Read images from disk, pad/resize them, and return
|
||||
X : ndarray [N, 3, H, W] (float32, 0‑1)
|
||||
y : ndarray [N] (float32)
|
||||
"""
|
||||
X, y = [], []
|
||||
|
||||
for path, label in zip(files, labels):
|
||||
|
||||
# ─── 1. load as RGB -------------------------------------------------
|
||||
with Image.open(path) as im:
|
||||
im = im.convert("RGB") # guarantees 3 channels
|
||||
img = np.array(im) # H×W×3 uint8
|
||||
|
||||
# ─── 2. pad / resize (your helper) --------------------------------
|
||||
img = pad_image_and_resize(img, target_image_size) # still returns H×W×3
|
||||
|
||||
# ─── 3. to CHW + normalise -----------------------------------------
|
||||
img = np.transpose(img, (2, 0, 1)).astype(np.float32) / 255.0
|
||||
|
||||
X.append(img)
|
||||
y.append(label)
|
||||
|
||||
X = np.stack(X, axis=0).astype(np.float32) # (N, 3, H, W)
|
||||
y = np.asarray(y, dtype=np.float32) # (N,)
|
||||
|
||||
return X, y
|
||||
|
||||
def train_and_validate(model, optimizer, criterion,
|
||||
train_loader, val_loader,
|
||||
epochs, patience, device):
|
||||
best_val_acc, best_state, patience_ctr = 0.0, None, 0
|
||||
|
||||
for epoch in range(epochs):
|
||||
model.train()
|
||||
running = 0.0
|
||||
for images, labels in train_loader:
|
||||
images = images.to(device)
|
||||
labels = labels.to(device).float()
|
||||
|
||||
out = model(images) # (B, 1)
|
||||
loss = criterion(out, labels.unsqueeze(1))
|
||||
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
running += loss.item() * images.size(0)
|
||||
|
||||
val_acc = evaluate(model, val_loader, device)
|
||||
print(f"Epoch {epoch+1:3d} · train‑loss {running/len(train_loader.dataset):.4f} · "
|
||||
f"val‑acc {val_acc:.4f}")
|
||||
|
||||
if val_acc > best_val_acc:
|
||||
best_val_acc, best_state = val_acc, model.state_dict()
|
||||
patience_ctr = 0
|
||||
else:
|
||||
patience_ctr += 1
|
||||
if patience_ctr >= patience or val_acc == 1.0:
|
||||
break
|
||||
|
||||
if best_state is not None:
|
||||
model.load_state_dict(best_state)
|
||||
return best_val_acc, model
|
||||
|
||||
|
||||
def evaluate(model, loader, device):
|
||||
model.eval()
|
||||
correct, total = 0, 0
|
||||
with torch.no_grad():
|
||||
for images, labels in loader:
|
||||
images = images.to(device)
|
||||
labels = labels.to(device).float()
|
||||
|
||||
out = model(images) # (B, 1)
|
||||
preds = (out > 0.5).float().squeeze(1) # (B)
|
||||
correct += (preds == labels).sum().item()
|
||||
total += labels.size(0)
|
||||
return correct / total if total else 0.0
|
||||
|
||||
|
||||
|
||||
def create_train_val_test_sets(target_image_size, dataset_path):
|
||||
print("Data preparation with parameters:")
|
||||
print(" target_image_size:", target_image_size)
|
||||
print(" dataset_path:", dataset_path)
|
||||
|
||||
train_files, train_labels = get_data_from_path(os.path.join(dataset_path, "train"))
|
||||
val_files, val_labels = get_data_from_path(os.path.join(dataset_path, "val"))
|
||||
|
||||
X_train, y_train = load_dataset(train_files, train_labels, target_image_size)
|
||||
X_val, y_val = load_dataset(val_files, val_labels, target_image_size)
|
||||
|
||||
|
||||
# Load test data from subfolders.
|
||||
test_folder = os.path.join(dataset_path, "test")
|
||||
test_datasets_dict = get_test_datasets_from_path(test_folder)
|
||||
X_test_dict = {}
|
||||
y_test_dict = {}
|
||||
global_X_test_list = []
|
||||
global_y_test_list = []
|
||||
for subfolder, (files, labels) in test_datasets_dict.items():
|
||||
X_sub, y_sub = load_dataset(files, labels, target_image_size)
|
||||
X_test_dict[subfolder] = X_sub
|
||||
y_test_dict[subfolder] = y_sub
|
||||
global_X_test_list.append(X_sub)
|
||||
global_y_test_list.append(y_sub)
|
||||
global_X_test = np.concatenate(global_X_test_list, axis=0) if global_X_test_list else np.array([])
|
||||
global_y_test = np.concatenate(global_y_test_list, axis=0) if global_y_test_list else np.array([])
|
||||
|
||||
print("Instances per datasets:")
|
||||
print(" Train set:", len(X_train))
|
||||
print(" Validation set:", len(X_val))
|
||||
print(" Global Test set:", len(global_X_test))
|
||||
print(" Test subsets:", {key: len(sub) for key, sub in y_test_dict.items()})
|
||||
|
||||
return X_train, y_train, X_val, y_val, global_X_test, global_y_test, X_test_dict, y_test_dict
|
||||
|
||||
def reset_random_seeds(seed):
|
||||
os.environ['PYTHONHASHSEED'] = str(seed)
|
||||
os.environ["PL_GLOBAL_SEED"] = str(seed)
|
||||
np.random.seed(seed)
|
||||
random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
torch.backends.cudnn.deterministic = True
|
||||
torch.backends.cudnn.benchmark = False
|
||||
|
||||
# -------------------------------
|
||||
class ExperimentPipeline:
|
||||
def __init__(self, X_train, y_train, X_val, y_val,
|
||||
X_test_global, y_test_global,
|
||||
X_test_dict, y_test_dict,
|
||||
device):
|
||||
self.device = device
|
||||
self.X_train = torch.tensor(X_train, dtype=torch.float32)
|
||||
self.y_train = torch.tensor(y_train, dtype=torch.float32)
|
||||
self.X_val = torch.tensor(X_val, dtype=torch.float32)
|
||||
self.y_val = torch.tensor(y_val, dtype=torch.float32)
|
||||
self.X_test_global = (torch.tensor(X_test_global, dtype=torch.float32)
|
||||
if X_test_global.size else None)
|
||||
self.y_test_global = (torch.tensor(y_test_global, dtype=torch.float32)
|
||||
if y_test_global.size else None)
|
||||
self.X_test_dict = {k: torch.tensor(v, dtype=torch.float32)
|
||||
for k, v in X_test_dict.items()}
|
||||
self.y_test_dict = {k: torch.tensor(v, dtype=torch.float32)
|
||||
for k, v in y_test_dict.items()}
|
||||
|
||||
# --------------------------------------------------------------------
|
||||
def run_full_experiment(self,
|
||||
rnn_hidden, cls_hidden, rnn_type, dropout,
|
||||
learning_rate, epochs, batch_size,
|
||||
model_save_path, log_path,
|
||||
configuration_name, patience):
|
||||
|
||||
print(f"\n▶ {configuration_name} | rnn={rnn_type}-{rnn_hidden} | "
|
||||
f"cls={cls_hidden} | drop={dropout} | lr={learning_rate} | "
|
||||
f"batch={batch_size}")
|
||||
|
||||
# ─── build model ─────────────────────────────────────────
|
||||
model = ImageSequenceClassifier(
|
||||
rnn_hidden=rnn_hidden,
|
||||
cls_hidden=cls_hidden,
|
||||
dropout=dropout,
|
||||
rnn_type=rnn_type
|
||||
).to(self.device)
|
||||
|
||||
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
||||
criterion = nn.BCELoss()
|
||||
|
||||
train_loader = DataLoader(TensorDataset(self.X_train, self.y_train),
|
||||
batch_size=batch_size, shuffle=True)
|
||||
val_loader = DataLoader(TensorDataset(self.X_val, self.y_val),
|
||||
batch_size=batch_size, shuffle=False)
|
||||
|
||||
best_val_acc, model = train_and_validate(model, optimizer, criterion,
|
||||
train_loader, val_loader,
|
||||
epochs, patience, self.device)
|
||||
print(f" best‑val‑acc = {best_val_acc:.4f}")
|
||||
|
||||
# ─── global test ────────────────────────────────────────
|
||||
if self.X_test_global is not None:
|
||||
g_loader = DataLoader(TensorDataset(self.X_test_global,
|
||||
self.y_test_global),
|
||||
batch_size=batch_size, shuffle=False)
|
||||
g_acc = evaluate(model, g_loader, self.device)
|
||||
print(f" global‑test‑acc = {g_acc:.4f}")
|
||||
else:
|
||||
g_acc = None
|
||||
print(" global‑test‑set empty")
|
||||
|
||||
# ─── per‑folder test ────────────────────────────────────
|
||||
sub_acc = {}
|
||||
for name, X_sub in self.X_test_dict.items():
|
||||
if X_sub.numel() == 0:
|
||||
sub_acc[name] = None
|
||||
continue
|
||||
loader = DataLoader(TensorDataset(X_sub, self.y_test_dict[name]),
|
||||
batch_size=batch_size, shuffle=False)
|
||||
sub_acc[name] = evaluate(model, loader, self.device)
|
||||
print(f" {name:>12s} : {sub_acc[name]:.4f}")
|
||||
|
||||
# ─── save ───────────────────────────────────────────────
|
||||
mname = f"{configuration_name}_val_{best_val_acc:.4f}.pt"
|
||||
if model_save_path:
|
||||
torch.save(model.state_dict(), os.path.join(model_save_path, mname))
|
||||
with open(os.path.join(log_path, "experiment_results.txt"), "a") as f:
|
||||
f.write(f"{mname}, {best_val_acc:.4f}, {g_acc}, {sub_acc}\n")
|
||||
|
||||
|
||||
# --------------------------------------- MAIN ----------------------------------------------
|
||||
|
||||
#TODO: Einfach mal mit mehr testbildern.
|
||||
|
||||
def main():
|
||||
mySeed = 42
|
||||
reset_random_seeds(mySeed)
|
||||
|
||||
model_save_path = None
|
||||
log_path = "C:/Users/bijan/Desktop/efficient_surface_anomaly_detector/log_seq_model/"
|
||||
dataset_path = "C:/Users/bijan/Desktop/efficient_surface_anomaly_detector/data/dataset_for_paper_object/"
|
||||
|
||||
os.makedirs(log_path, exist_ok=True)
|
||||
if model_save_path:
|
||||
os.makedirs(model_save_path, exist_ok=True)
|
||||
|
||||
# ─── search grids ──────────────────────────────────────────
|
||||
epochs = 100
|
||||
patience = 25
|
||||
batch_size = 256
|
||||
learning_rates = [1e-3]
|
||||
rnn_hidden_list = [8, 16, 32, 64, 128]
|
||||
cls_hidden_list = [8, 16, 32, 64, 128]
|
||||
rnn_type_list = ["GRU", "LSTM"]
|
||||
dropout_list = [0.0, 0.2, 0.5]
|
||||
image_sizes = [394] #256, 394
|
||||
|
||||
# ─── bookkeeping ───────────────────────────────────────────
|
||||
checkpoint_file = os.path.join(log_path, "checkpoint_seq.txt")
|
||||
done = set(open(checkpoint_file).read().splitlines()) if os.path.exists(checkpoint_file) else set()
|
||||
|
||||
# ─── grid search loop ──────────────────────────────────────
|
||||
for img_sz in image_sizes:
|
||||
X_tr, y_tr, X_va, y_va, X_te, y_te, X_dict, y_dict = \
|
||||
create_train_val_test_sets(img_sz, dataset_path)
|
||||
|
||||
for lr in learning_rates:
|
||||
for rnn_h in rnn_hidden_list:
|
||||
for cls_h in cls_hidden_list:
|
||||
for rnn_t in rnn_type_list:
|
||||
for drop in dropout_list:
|
||||
|
||||
cfg = f"sz{img_sz}_lr{lr}_rnn{rnn_t}{rnn_h}_cls{cls_h}_drop{drop}"
|
||||
if cfg in done:
|
||||
print("skip", cfg)
|
||||
continue
|
||||
|
||||
pipe = ExperimentPipeline(X_tr, y_tr, X_va, y_va,
|
||||
X_te, y_te, X_dict, y_dict,
|
||||
device)
|
||||
pipe.run_full_experiment(
|
||||
rnn_hidden=rnn_h, cls_hidden=cls_h,
|
||||
rnn_type=rnn_t, dropout=drop,
|
||||
learning_rate=lr, epochs=epochs,
|
||||
batch_size=batch_size, model_save_path=model_save_path,
|
||||
log_path=log_path, configuration_name=cfg,
|
||||
patience=patience
|
||||
)
|
||||
|
||||
with open(checkpoint_file, "a") as f:
|
||||
f.write(cfg + "\n")
|
||||
|
||||
reset_random_seeds(mySeed)
|
||||
gc.collect()
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,99 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
class ColumnFeatureExtractor(nn.Module):
|
||||
"""
|
||||
Input : (B, 1, H, W) – single‑channel image
|
||||
Output : (B, W, 2) – per‑column [mean, var] features
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def forward(self, x):
|
||||
# x is already grayscale: (B, 1, H, W)
|
||||
mean = x.mean(dim=2) # (B, 1, W)
|
||||
var = x.var(dim=2, unbiased=False) # (B, 1, W)
|
||||
feat = torch.cat([mean, var], dim=1) # (B, 2, W)
|
||||
return feat.permute(0, 2, 1) # (B, W, 2)
|
||||
|
||||
|
||||
class ImageSequenceClassifier(nn.Module):
|
||||
"""
|
||||
RGB/gray image ➜ convert to gray ➜ column stats ➜ GRU/LSTM ➜ sigmoid
|
||||
"""
|
||||
GRAY_WEIGHTS = 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.0):
|
||||
super().__init__()
|
||||
|
||||
self.register_buffer("gray_w", self.GRAY_WEIGHTS) # moved to device automatically
|
||||
self.feature_extractor = ColumnFeatureExtractor() # always outputs 2‑D features
|
||||
|
||||
rnn_cls = nn.GRU if rnn_type.upper() == "GRU" else nn.LSTM
|
||||
self.rnn = rnn_cls(input_size=2, # [mean, var]
|
||||
hidden_size=rnn_hidden,
|
||||
batch_first=True)
|
||||
|
||||
self.head = nn.Sequential(
|
||||
nn.Linear(rnn_hidden, cls_hidden),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(dropout),
|
||||
nn.Linear(cls_hidden, 1),
|
||||
nn.Sigmoid()
|
||||
)
|
||||
|
||||
# ─────────────────────────────────────────────────────────
|
||||
def rgb_to_gray(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Accepts (B,3,H,W) or (B,1,H,W) and returns (B,1,H,W)
|
||||
without changing the original dtype/range.
|
||||
"""
|
||||
if x.shape[1] == 3:
|
||||
w = self.gray_w.to(dtype=x.dtype, device=x.device)
|
||||
x = (x * w).sum(dim=1, keepdim=True)
|
||||
return x
|
||||
|
||||
# ─────────────────────────────────────────────────────────
|
||||
def forward(self, x):
|
||||
"""
|
||||
x : (B, C, H, W) where C is 1 or 3
|
||||
"""
|
||||
x_gray = self.rgb_to_gray(x) # (B, 1, H, W)
|
||||
seq = self.feature_extractor(x_gray) # (B, W, 2)
|
||||
seq_out, _ = self.rnn(seq) # (B, W, hidden)
|
||||
last = seq_out[:, -1, :] # final column’s hidden state
|
||||
return self.head(last) # (B, 1)
|
||||
|
||||
|
||||
# -----------------------------------------------------------
|
||||
# quick smoke‑test
|
||||
def main():
|
||||
torch.manual_seed(0)
|
||||
B, H, W = 2, 128, 128
|
||||
|
||||
imgs_rgb = torch.rand(B, 3, H, W) # random RGB batch
|
||||
imgs_gray = torch.rand(B, 1, H, W) # random grayscale batch
|
||||
|
||||
model = ImageSequenceClassifier(rnn_hidden=64,
|
||||
cls_hidden=32,
|
||||
dropout=0.2)
|
||||
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
p_rgb = model(imgs_rgb)
|
||||
p_gray = model(imgs_gray)
|
||||
|
||||
for i, p in enumerate(p_rgb.squeeze(1)):
|
||||
print(f"[RGB ] image {i}: sigmoid = {p:.4f}")
|
||||
for i, p in enumerate(p_gray.squeeze(1)):
|
||||
print(f"[Gray] image {i}: sigmoid = {p:.4f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user