371 lines
17 KiB
Python
371 lines
17 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 model4 import ForeignObjectClassificationModel
|
||
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, num_tiles):
|
||
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)
|
||
|
||
# ─── forward ───────────────────────────────────────────
|
||
out = model(images) # [B, N]
|
||
tgt = labels.unsqueeze(1).repeat(1, num_tiles) # [B, N]
|
||
loss = criterion(out, tgt)
|
||
|
||
optimizer.zero_grad()
|
||
loss.backward()
|
||
optimizer.step()
|
||
running += loss.item() * images.size(0)
|
||
|
||
# ─── validation ───────────────────────────────────────────
|
||
val_acc = evaluate(model, val_loader, criterion, device, num_tiles)
|
||
print(f"Epoch {epoch+1:3d} · train‑loss {running/len(train_loader.dataset):.4f} · 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, criterion, device, num_tiles):
|
||
model.eval()
|
||
correct, total = 0, 0
|
||
with torch.no_grad():
|
||
for images, labels in loader:
|
||
images = images.to(device)
|
||
labels = labels.to(device)
|
||
|
||
out = model(images) # [B, N]
|
||
loss = criterion(out, labels.unsqueeze(1).repeat(1, num_tiles))
|
||
# image‑level decision : object present ⇔ any tile > 0.5
|
||
preds = (out > 0.5).any(dim=1).float() # [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, num_tiles_per_side, dataset_path):
|
||
print("Data preparation with parameters:")
|
||
print(" target_image_size:", target_image_size)
|
||
print(" num_tiles_per_side:", num_tiles_per_side)
|
||
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 > 0 else None
|
||
self.y_test_global = torch.tensor(y_test_global, dtype=torch.float32) if y_test_global.size > 0 else None
|
||
self.X_test_dict = {key: torch.tensor(val, dtype=torch.float32) for key, val in X_test_dict.items()}
|
||
self.y_test_dict = {key: torch.tensor(val, dtype=torch.float32) for key, val in y_test_dict.items()}
|
||
|
||
def run_full_experiment(self,
|
||
num_tiles_per_side,
|
||
kernel_size,
|
||
num_conv_layers,
|
||
pooling_after_each_conv,
|
||
conv_pooling_type,
|
||
global_pooling_type,
|
||
learning_rate,
|
||
epochs,
|
||
batch_size,
|
||
model_save_path,
|
||
log_path,
|
||
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} "
|
||
f"| lr={learning_rate} | batch={batch_size}")
|
||
|
||
# ─── build model ───────────────────────────────────────────
|
||
model = ForeignObjectClassificationModel(
|
||
num_tiles_per_side = num_tiles_per_side,
|
||
kernel_size = kernel_size,
|
||
num_conv_layers = num_conv_layers,
|
||
pooling_after_each_conv= pooling_after_each_conv,
|
||
conv_pooling_type = conv_pooling_type,
|
||
global_pooling_type = global_pooling_type
|
||
).to(self.device)
|
||
|
||
num_tiles = num_tiles_per_side ** 2
|
||
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
||
criterion = nn.BCELoss()
|
||
|
||
# ─── data loaders ─────────────────────────────────────────
|
||
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)
|
||
|
||
# ─── train / validate ─────────────────────────────────────
|
||
best_val_acc, model = train_and_validate(model, optimizer, criterion,
|
||
train_loader, val_loader,
|
||
epochs, patience=patience,
|
||
device=self.device,
|
||
num_tiles=num_tiles)
|
||
print(f" best‑val‑acc = {best_val_acc:.4f}")
|
||
|
||
# ─── GLOBAL test set ──────────────────────────────────────
|
||
if self.X_test_global is not None:
|
||
test_loader = DataLoader(TensorDataset(self.X_test_global,
|
||
self.y_test_global),
|
||
batch_size=batch_size, shuffle=False)
|
||
global_test_acc = evaluate(model, test_loader, criterion,
|
||
self.device, num_tiles)
|
||
print(f" global‑test‑acc = {global_test_acc:.4f}")
|
||
else:
|
||
global_test_acc = None
|
||
print(" global‑test‑set empty")
|
||
|
||
# ─── PER‑SUBFOLDER evaluation ────────────────────────────
|
||
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, criterion,
|
||
self.device, num_tiles)
|
||
print(f" {name:>12s} : {sub_acc[name]:.4f}")
|
||
|
||
# ─── save ────────────────────────────────────────────────
|
||
mod_name = f"{configuration_name}_val_{best_val_acc:.4f}.pt"
|
||
if model_save_path:
|
||
torch.save(model.state_dict(), os.path.join(model_save_path, mod_name))
|
||
with open(os.path.join(log_path, "experiment_results.txt"), "a") as f:
|
||
f.write(f"{mod_name}, {best_val_acc:.4f}, {global_test_acc}, {sub_acc}\n")
|
||
|
||
|
||
def main():
|
||
mySeed = 42
|
||
reset_random_seeds(mySeed)
|
||
model_save_path = None # Update as needed
|
||
log_path = "C:/Users/bijan/Desktop/efficient_surface_anomaly_detector/log_patch_model" # Update as needed
|
||
dataset_path = "C:/Users/bijan/Desktop/efficient_surface_anomaly_detector/data/dataset_for_paper_object/" # Update as needed
|
||
|
||
if model_save_path is not None:
|
||
os.makedirs(model_save_path, exist_ok=True)
|
||
os.makedirs(log_path, exist_ok=True)
|
||
|
||
checkpoint_file = os.path.join(log_path, "checkpoint.txt")
|
||
completed_experiments = set()
|
||
if os.path.exists(checkpoint_file):
|
||
with open(checkpoint_file, "r") as f:
|
||
for line in f:
|
||
completed_experiments.add(line.strip())
|
||
print(f"Resuming: {len(completed_experiments)} experiments completed.")
|
||
else:
|
||
print("No checkpoint found. Starting new experiments.")
|
||
|
||
#TODO: if that works somehow, than sequence classifier
|
||
|
||
epochs = 1000
|
||
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] #, 32, 16, 8, 4]
|
||
kernel_sizes = [3]
|
||
num_conv_layers_list = [4]#, 3, 2, 1]
|
||
|
||
# ────────────────────────────────────────────────────────────────
|
||
for lr in learning_rates:
|
||
for img_sz in target_image_sizes:
|
||
for tiles in n_tiles_per_side_list:
|
||
|
||
X_train, y_train, X_val, y_val, \
|
||
X_test, y_test, X_test_dict, y_test_dict = create_train_val_test_sets(
|
||
target_image_size = img_sz,
|
||
num_tiles_per_side = tiles,
|
||
dataset_path = dataset_path)
|
||
|
||
data_tag = f"lr_{lr}_img{img_sz}_tiles{tiles}"
|
||
|
||
for ks in kernel_sizes:
|
||
for n_layers in num_conv_layers_list:
|
||
for pool_conv in pooling_after_each_conv_list:
|
||
for conv_pool_t in conv_pooling_type_list:
|
||
for glob_pool_t in global_pooling_type_list:
|
||
|
||
cfg_name = (f"{data_tag}_ks{ks}_layers{n_layers}_"
|
||
f"pc{int(pool_conv)}_{conv_pool_t}_{glob_pool_t}")
|
||
|
||
if cfg_name in completed_experiments:
|
||
print("skip", cfg_name)
|
||
continue
|
||
|
||
ep = ExperimentPipeline(X_train, y_train,
|
||
X_val, y_val,
|
||
X_test, y_test,
|
||
X_test_dict, y_test_dict,
|
||
device)
|
||
ep.run_full_experiment(num_tiles_per_side = tiles,
|
||
kernel_size = ks,
|
||
num_conv_layers = n_layers,
|
||
pooling_after_each_conv = pool_conv,
|
||
conv_pooling_type = conv_pool_t,
|
||
global_pooling_type= glob_pool_t,
|
||
learning_rate = lr,
|
||
epochs = epochs,
|
||
batch_size = batch_size,
|
||
model_save_path = model_save_path,
|
||
log_path = log_path,
|
||
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__':
|
||
main() |