335 lines
15 KiB
Python
335 lines
15 KiB
Python
import os
|
|
import numpy as np
|
|
import cv2
|
|
from PIL import Image
|
|
import torch
|
|
import torch.nn as nn
|
|
import torch.optim as optim
|
|
from torch.utils.data import DataLoader, TensorDataset
|
|
from data_adapter import load_and_grayscale, pad_image_and_resize, tile_and_stack
|
|
from model import ForeignObjectClassificationModel
|
|
|
|
# --- GPU Setup ---
|
|
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
|
print("Using device:", device)
|
|
if device.type == 'cuda':
|
|
print("GPU enabled")
|
|
else:
|
|
print("No GPU found")
|
|
|
|
def load_dataset(image_paths, labels, target_size, num_tiles_per_side):
|
|
X, y = [], []
|
|
for path, label in zip(image_paths, labels):
|
|
gray_img = load_and_grayscale(path) # shape: (H, W)
|
|
resized_img = pad_image_and_resize(gray_img, target_size) # shape: (target_size, target_size)
|
|
img_tiled = tile_and_stack(resized_img, num_tiles_per_side) # shape: (num_tiles, tile_size, tile_size)
|
|
# Rearrange tiles to the channel dimension (channels-last -> channels-first later)
|
|
img_tiled = np.moveaxis(img_tiled, 0, -1) # shape: (tile_size, tile_size, num_tiles)
|
|
X.append(img_tiled)
|
|
y.append(label)
|
|
X = np.array(X) # (N, H, W, C)
|
|
y = np.array(y)
|
|
# Convert to channels-first format: (N, C, H, W)
|
|
X = np.transpose(X, (0, 3, 1, 2))
|
|
return X, y
|
|
|
|
def train_and_validate(model, optimizer, criterion, train_loader, val_loader, epochs, patience, device):
|
|
best_val_acc = 0.0
|
|
best_model_state = None
|
|
patience_counter = 0
|
|
|
|
for epoch in range(epochs):
|
|
model.train()
|
|
train_loss = 0.0 # Never used
|
|
|
|
for tile_images, labels in train_loader:
|
|
tile_images = tile_images.to(device)
|
|
labels = labels.to(device).float() # ensure float type for BCELoss
|
|
optimizer.zero_grad()
|
|
outputs = model(tile_images)
|
|
loss = criterion(outputs, labels.unsqueeze(1))
|
|
loss.backward()
|
|
optimizer.step()
|
|
train_loss += loss.item() * tile_images.size(0) # Never used
|
|
|
|
model.eval()
|
|
val_acc = None
|
|
with torch.no_grad():
|
|
val_acc = evaluate(model, val_loader, criterion, device)
|
|
|
|
#print(f"Epoch {epoch+1}/{epochs} | Train Loss: {train_loss:.4f} | Val Acc: {val_acc:.4f}")
|
|
|
|
# Early stopping based on validation accuracy improvement
|
|
if val_acc > best_val_acc:
|
|
best_val_acc = val_acc
|
|
best_model_state = model.state_dict()
|
|
patience_counter = 0
|
|
else:
|
|
patience_counter += 1
|
|
|
|
if patience_counter >= patience:
|
|
print("Early stopping triggered.")
|
|
break
|
|
|
|
# Load the best model state before returning
|
|
if best_model_state is not None:
|
|
model.load_state_dict(best_model_state)
|
|
|
|
return best_val_acc, model
|
|
|
|
def evaluate(model, test_loader, criterion, device):
|
|
model.eval()
|
|
test_loss = 0.0 #Not used
|
|
test_correct = 0
|
|
test_total = 0
|
|
with torch.no_grad():
|
|
for inputs, targets in test_loader:
|
|
inputs = inputs.to(device)
|
|
targets = targets.to(device).float()
|
|
outputs = model(inputs)
|
|
loss = criterion(outputs, targets.unsqueeze(1)) # Not used
|
|
test_loss += loss.item() * inputs.size(0)
|
|
preds = (outputs > 0.5).float()
|
|
test_correct += (preds.squeeze(1) == targets).sum().item()
|
|
test_total += targets.size(0)
|
|
test_acc = test_correct / test_total if test_total > 0 else 0
|
|
return test_acc
|
|
|
|
|
|
class ExperimentPipeline:
|
|
def __init__(self, X_train, y_train, X_val, y_val, X_test, y_test, device):
|
|
self.device = device
|
|
# Convert numpy arrays to torch tensors
|
|
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 = torch.tensor(X_test, dtype=torch.float32)
|
|
self.y_test = torch.tensor(y_test, dtype=torch.float32)
|
|
|
|
def run_full_experiment(self, output_channels_ds_conv, kernel_size,
|
|
hidden_units, dropout_rate, learning_rate, epochs,
|
|
batch_size, model_save_path, log_path, data_parameters):
|
|
print(f"Running experiment with parameters {data_parameters}, "
|
|
f"output_channels_ds_conv={output_channels_ds_conv}, kernel_size={kernel_size}, "
|
|
f"hidden_units={hidden_units}, dropout_rate={dropout_rate}, "
|
|
f"learning_rate={learning_rate}, epochs={epochs}, batch_size={batch_size}, "
|
|
f"model_save_path={model_save_path}, log_path={log_path}")
|
|
|
|
# X_train shape: (N, C, H, W)
|
|
input_shape = self.X_train.shape[1:]
|
|
print("Model input shape:", input_shape)
|
|
input_channels = input_shape[0]
|
|
|
|
model = ForeignObjectClassificationModel(
|
|
input_channels=input_channels,
|
|
output_channels_ds_conv=output_channels_ds_conv,
|
|
kernel_size=kernel_size,
|
|
hidden_units=hidden_units,
|
|
dropout_rate=dropout_rate
|
|
)
|
|
model.to(self.device)
|
|
|
|
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
|
criterion = nn.BCELoss()
|
|
|
|
# Create DataLoaders
|
|
train_dataset = TensorDataset(self.X_train, self.y_train)
|
|
val_dataset = TensorDataset(self.X_val, self.y_val)
|
|
test_dataset = TensorDataset(self.X_test, self.y_test)
|
|
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
|
|
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
|
|
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
|
|
|
|
print("Running training and validation...")
|
|
best_val_acc, model = train_and_validate(model, optimizer, criterion,
|
|
train_loader, val_loader,
|
|
epochs=epochs, patience=100, device=self.device)
|
|
|
|
print(f"Best validation accuracy: {best_val_acc:.4f}")
|
|
|
|
print("Running evaluation on test set...")
|
|
test_acc = evaluate(model, test_loader, criterion, self.device)
|
|
print(f"Test accuracy: {test_acc:.4f}")
|
|
|
|
# Save the model; using .pt extension for PyTorch models
|
|
model_name = (f"{data_parameters}_ks_{kernel_size}_oc_{output_channels_ds_conv}_hu_{hidden_units}"
|
|
f"_dr_{dropout_rate}_val_{best_val_acc:.4f}_test_{test_acc:.4f}.pt")
|
|
|
|
#Save model only if path to folder is not none
|
|
if model_save_path is not None:
|
|
torch.save(model.state_dict(), os.path.join(model_save_path, model_name))
|
|
|
|
with open(os.path.join(log_path, "experiment_results.txt"), "a") as file_handle:
|
|
file_handle.write(f"{model_name}, "
|
|
f"{best_val_acc:.4f},"
|
|
f"{test_acc:.4f}\n")
|
|
|
|
print(f'Model trained, evaluated and saved as {model_name}')
|
|
|
|
|
|
def create_train_val_test_sets(image_folder, n_train_val_images_per_class, train_val_ratio,
|
|
n_test_images_per_class, target_image_size, num_tiles_per_side):
|
|
print("Data preparation with parameters:")
|
|
print(" image_folder:", image_folder)
|
|
print(" n_train_val_images_per_class:", n_train_val_images_per_class)
|
|
print(" train_val_ratio:", train_val_ratio)
|
|
print(" n_test_images_per_class:", n_test_images_per_class)
|
|
print(" target_image_size:", target_image_size)
|
|
print(" num_tiles_per_side:", num_tiles_per_side)
|
|
print(" Tile size:", target_image_size // num_tiles_per_side)
|
|
print(" Amount of tiles:", num_tiles_per_side ** 2)
|
|
image_files = [os.path.join(image_folder, f) for f in os.listdir(image_folder)]
|
|
labels = [1 if 'fo_' in f else 0 for f in image_files]
|
|
|
|
# Separate images by class
|
|
class_0 = [f for f, lbl in zip(image_files, labels) if lbl == 0]
|
|
class_1 = [f for f, lbl in zip(image_files, labels) if lbl == 1]
|
|
|
|
if len(class_0) < n_train_val_images_per_class + n_test_images_per_class or \
|
|
len(class_1) < n_train_val_images_per_class + n_test_images_per_class:
|
|
raise ValueError("Not enough images per class to fulfill requested dataset sizes!")
|
|
|
|
# Shuffle classes
|
|
np.random.shuffle(class_0)
|
|
np.random.shuffle(class_1)
|
|
# Extract train_val images per class
|
|
train_val_0 = class_0[:n_train_val_images_per_class]
|
|
train_val_1 = class_1[:n_train_val_images_per_class]
|
|
|
|
# Split into train and validation per class
|
|
split_idx_0 = int(len(train_val_0) * train_val_ratio)
|
|
split_idx_1 = int(len(train_val_1) * train_val_ratio)
|
|
train_files = train_val_0[:split_idx_0] + train_val_1[:split_idx_1]
|
|
val_files = train_val_0[split_idx_0:] + train_val_1[split_idx_1:]
|
|
train_labels = [0] * split_idx_0 + [1] * split_idx_1
|
|
val_labels = [0] * (len(train_val_0) - split_idx_0) + [1] * (len(train_val_1) - split_idx_1)
|
|
|
|
# Prepare test set
|
|
test_files = (class_0[n_train_val_images_per_class:n_train_val_images_per_class + n_test_images_per_class] +
|
|
class_1[n_train_val_images_per_class:n_train_val_images_per_class + n_test_images_per_class])
|
|
test_labels = [0] * n_test_images_per_class + [1] * n_test_images_per_class
|
|
|
|
# Load datasets (with conversion to channels-first)
|
|
X_train, y_train = load_dataset(train_files, train_labels, target_image_size, num_tiles_per_side)
|
|
X_val, y_val = load_dataset(val_files, val_labels, target_image_size, num_tiles_per_side)
|
|
X_test, y_test = load_dataset(test_files, test_labels, target_image_size, num_tiles_per_side)
|
|
|
|
print("Instances per datasets:")
|
|
print(" Train set:", len(X_train))
|
|
print(" Validation set:", len(X_val))
|
|
print(" Test set:", len(X_test))
|
|
|
|
return X_train, y_train, X_val, y_val, X_test, y_test
|
|
|
|
|
|
#TODO ggf. Zweite Layer beim Modell setzen.
|
|
if __name__ == '__main__':
|
|
# Set random seeds for reproducibility
|
|
random_seed = 42
|
|
os.environ['PYTHONHASHSEED'] = str(random_seed)
|
|
np.random.seed(random_seed)
|
|
torch.manual_seed(random_seed)
|
|
if torch.cuda.is_available():
|
|
torch.cuda.manual_seed_all(random_seed)
|
|
|
|
# Update these paths as needed
|
|
image_folder = "C:/Users/bijan/Desktop/efficient_surface_anomaly_detector/data/our_fod_dataset/" # path to your images
|
|
model_save_path = None # "C:/Users/bijan/Desktop/efficient_surface_anomaly_detector/models/" # path to save the model
|
|
log_path = "C:/Users/bijan/Desktop/efficient_surface_anomaly_detector/log/" # path to save the logs
|
|
|
|
# Ensure necessary directories exist
|
|
if model_save_path is not None:
|
|
os.makedirs(model_save_path, exist_ok=True)
|
|
os.makedirs(log_path, exist_ok=True)
|
|
|
|
# Load or create a checkpoint file to keep track of completed experiments.
|
|
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 from checkpoint: {len(completed_experiments)} experiments already completed.")
|
|
else:
|
|
print("No checkpoint found. Starting new experiments.")
|
|
|
|
train_val_ratio = 0.5
|
|
n_test_images_per_class = 1000
|
|
|
|
n_train_val_images_per_class_list = [10, 25, 50] #, 75, 100]
|
|
target_image_sizes = [64, 128, 256]#, 512]
|
|
n_tiles_per_side_list = [2, 4, 8, 16, 32, 64]
|
|
|
|
output_channels_ds_conv_list = [8, 16, 32, 64, 128, 256]
|
|
kernel_sizes = [3, 5, 7, 9]
|
|
hidden_units_list = [16, 32, 64, 128, 256]
|
|
dropout_rates = [0.0, 0.25, 0.5, 0.75]
|
|
|
|
num_experiments = (len(n_train_val_images_per_class_list) * len(target_image_sizes) *
|
|
len(n_tiles_per_side_list) * len(output_channels_ds_conv_list) *
|
|
len(kernel_sizes) * len(hidden_units_list) * len(dropout_rates))
|
|
progress_counter = 0
|
|
|
|
for n_train_val_images_per_class in n_train_val_images_per_class_list:
|
|
for target_image_size in target_image_sizes:
|
|
for n_tiles_per_side in n_tiles_per_side_list:
|
|
X_train, y_train, X_val, y_val, X_test, y_test = create_train_val_test_sets(
|
|
image_folder=image_folder,
|
|
n_train_val_images_per_class=n_train_val_images_per_class,
|
|
train_val_ratio=train_val_ratio,
|
|
n_test_images_per_class=n_test_images_per_class,
|
|
target_image_size=target_image_size,
|
|
num_tiles_per_side=n_tiles_per_side
|
|
)
|
|
|
|
data_parameters = (f"ntvimg_{n_train_val_images_per_class}_imgsz_{target_image_size}"
|
|
f"_ntiles_{n_tiles_per_side}")
|
|
|
|
learning_rate = 0.001
|
|
epochs = 1000
|
|
batch_size = n_train_val_images_per_class
|
|
|
|
for output_channels_ds_conv in output_channels_ds_conv_list:
|
|
for kernel_size in kernel_sizes:
|
|
for hidden_units in hidden_units_list:
|
|
for dropout_rate in dropout_rates:
|
|
# Construct a unique identifier for this experiment
|
|
experiment_id = (f"{data_parameters}_oc_{output_channels_ds_conv}"
|
|
f"_ks_{kernel_size}_hu_{hidden_units}_dr_{dropout_rate}")
|
|
# If the experiment has been completed already, skip it.
|
|
if experiment_id in completed_experiments:
|
|
print(f"Skipping completed experiment: {experiment_id}")
|
|
progress_counter += 1
|
|
continue
|
|
|
|
experiment_pipeline = ExperimentPipeline(
|
|
X_train, y_train, X_val, y_val, X_test, y_test, device=device
|
|
)
|
|
experiment_pipeline.run_full_experiment(
|
|
output_channels_ds_conv=output_channels_ds_conv,
|
|
kernel_size=kernel_size,
|
|
hidden_units=hidden_units,
|
|
dropout_rate=dropout_rate,
|
|
learning_rate=learning_rate,
|
|
epochs=epochs,
|
|
batch_size=batch_size,
|
|
model_save_path=model_save_path,
|
|
log_path=log_path,
|
|
data_parameters=data_parameters
|
|
)
|
|
|
|
# Save the experiment id to the checkpoint file immediately after completion
|
|
with open(checkpoint_file, "a") as f:
|
|
f.write(experiment_id + "\n")
|
|
completed_experiments.add(experiment_id)
|
|
|
|
print("Deleting current experiment_pipeline...")
|
|
del experiment_pipeline
|
|
progress_counter += 1
|
|
print(f"Progress: {progress_counter}/{num_experiments}, {((progress_counter / num_experiments) * 100):.2f}%")
|
|
print()
|
|
|
|
print("Deleting current datasets...")
|
|
del X_train, y_train, X_val, y_val, X_test, y_test
|