368 lines
17 KiB
Python
368 lines
17 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 pad_image_and_resize, tile_and_stack, load_image
|
|
from model import ForeignObjectClassificationModel
|
|
import random
|
|
|
|
|
|
# --- 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, grayscale):
|
|
X, y = [], []
|
|
for path, label in zip(image_paths, labels):
|
|
# Load image; optionally convert to grayscale.
|
|
img = load_image(path, grayscale=grayscale)
|
|
# Pad and resize the image.
|
|
resized_img = pad_image_and_resize(img, target_size)
|
|
# Tile the image.
|
|
img_tiled = tile_and_stack(resized_img, num_tiles_per_side)
|
|
|
|
if grayscale:
|
|
# For grayscale images, each tile is 2D.
|
|
# Move the tile axis to the channel position.
|
|
# From (num_tiles, tile_size, tile_size) -> (tile_size, tile_size, num_tiles)
|
|
img_tiled = np.moveaxis(img_tiled, 0, -1)
|
|
else:
|
|
# For color images, each tile is (tile_size, tile_size, 3).
|
|
# Rearrange to (num_tiles, 3, tile_size, tile_size)
|
|
img_tiled = np.transpose(img_tiled, (0, 3, 1, 2))
|
|
# Merge the tile and channel dimensions:
|
|
# New shape: (num_tiles * 3, tile_size, tile_size)
|
|
num_tiles, channels, H, W = img_tiled.shape
|
|
img_tiled = img_tiled.reshape(num_tiles * channels, H, W)
|
|
|
|
X.append(img_tiled)
|
|
y.append(label)
|
|
|
|
X = np.array(X)
|
|
y = np.array(y)
|
|
if grayscale:
|
|
# Convert from (N, tile_size, tile_size, num_tiles) to (N, num_tiles, tile_size, tile_size)
|
|
X = np.transpose(X, (0, 3, 1, 2))
|
|
# For color images, X is already in the desired shape.
|
|
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(f"Early stopping triggered at epoch {epoch+1} with val_acc={val_acc:.4f}")
|
|
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, grayscale):
|
|
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)
|
|
print(" grayscale:", grayscale)
|
|
image_files = sorted(os.listdir(image_folder))
|
|
image_files = [os.path.join(image_folder, f) for f in image_files]
|
|
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, grayscale)
|
|
X_val, y_val = load_dataset(val_files, val_labels, target_image_size, num_tiles_per_side, grayscale)
|
|
X_test, y_test = load_dataset(test_files, test_labels, target_image_size, num_tiles_per_side, grayscale)
|
|
|
|
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
|
|
|
|
|
|
def reset_random_seeds(seed=42):
|
|
os.environ['PYTHONHASHSEED'] = str(seed)
|
|
np.random.seed(seed)
|
|
random.seed(seed)
|
|
torch.manual_seed(seed)
|
|
if torch.cuda.is_available():
|
|
torch.cuda.manual_seed_all(seed)
|
|
torch.backends.cudnn.deterministic = True
|
|
torch.backends.cudnn.benchmark = False
|
|
|
|
|
|
if __name__ == '__main__':
|
|
reset_random_seeds(42)
|
|
|
|
# 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.")
|
|
#TODO: Wenn die Experimente durch sind, dann prüfen wie das Ergebnis dieser Zeile ist.
|
|
#gray_True_ntvimg_10_imgsz_128_ntiles_8_ks_3_oc_128_hu_128_dr_0.5_val_1.0000_test_0.9050.pt, 1.0000,0.9050
|
|
grayscales = [False, True]
|
|
train_val_ratio = 0.5
|
|
n_test_images_per_class = 1000
|
|
|
|
n_train_val_images_per_class_list = [10]
|
|
target_image_sizes = [128, 256, 512]
|
|
n_tiles_per_side_list = [4, 8, 16, 32]
|
|
|
|
output_channels_ds_conv_list = [32, 64, 128, 256]
|
|
kernel_sizes = [3, 5, 7, 9]
|
|
hidden_units_list = [32, 64, 128, 256]
|
|
dropout_rates = [0, 0.25, 0.5, 0.75] # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
|
|
|
|
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 grayscale in grayscales:
|
|
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,
|
|
grayscale=grayscale
|
|
)
|
|
|
|
data_parameters = (f"gray_{grayscale}_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
|
|
reset_random_seeds()
|
|
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()
|
|
torch.cuda.empty_cache()
|
|
print("Deleting current datasets...")
|
|
del X_train, y_train, X_val, y_val, X_test, y_test
|