335 lines
14 KiB
Python
335 lines
14 KiB
Python
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.
|
||
#TODO maybe transformer encoder
|
||
#TODO: notfalls altes modell nachbauen und dann sequenz modell darüber
|
||
|
||
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 = 1000
|
||
patience = 100
|
||
batch_size = 32
|
||
learning_rates = [0.001]
|
||
rnn_hidden_list = [16, 32, 64, 128]
|
||
cls_hidden_list = [16, 32, 64, 128]
|
||
rnn_type_list = ["GRU", "LSTM"]
|
||
dropout_list = [0.0, 0.2, 0.5]
|
||
image_sizes = [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() |