462 lines
23 KiB
Python
462 lines
23 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
|
|
import gc
|
|
|
|
|
|
# --- 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")
|
|
|
|
device = "cuda"
|
|
|
|
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 by patience at epoch {epoch+1} with val_acc={val_acc:.4f}")
|
|
break
|
|
if val_acc == 1.0:
|
|
print(f"Early stopping triggered by perfect accuracy 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, num_conv_layers, num_fc_layers,
|
|
hidden_units, dropout_rate, with_shuffle_channels, with_rotate_channels,
|
|
learning_rate, epochs, batch_size, model_save_path, log_path, configuration_name):
|
|
print(f"Running experiment for {configuration_name}, "
|
|
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,
|
|
conv_out_channels=output_channels_ds_conv,
|
|
kernel_size=kernel_size,
|
|
num_conv_layers=num_conv_layers,
|
|
num_fc_layers=num_fc_layers,
|
|
hidden_units=hidden_units,
|
|
dropout_rate=dropout_rate,
|
|
with_shuffle_channels=with_shuffle_channels,
|
|
with_rotate_channels=with_rotate_channels
|
|
)
|
|
|
|
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=200, 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"{configuration_name}_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 get_data_from_path(path):
|
|
ok_path = os.path.join(path, "ok")
|
|
nok_path = os.path.join(path, "nok")
|
|
ok_files = [os.path.join(ok_path, f) for f in os.listdir(ok_path)]
|
|
nok_files = [os.path.join(nok_path, f) for f in os.listdir(nok_path)]
|
|
ok_labels = [0] * len(ok_files)
|
|
nok_labels = [1] * len(nok_files)
|
|
return ok_files + nok_files, ok_labels + nok_labels
|
|
|
|
|
|
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, dataset_path):
|
|
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)
|
|
print(" dataset_path:", dataset_path)
|
|
|
|
X_train = None
|
|
y_train = None
|
|
X_val = None
|
|
y_val = None
|
|
X_test = None
|
|
y_test = None
|
|
|
|
if 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"))
|
|
test_files, test_labels = get_data_from_path(os.path.join(dataset_path, "test"))
|
|
# 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)
|
|
else:
|
|
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):
|
|
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
|
|
|
|
#NOTE: Vorteile für Nutzer
|
|
#Kein Object labelling nur cls
|
|
#Schneller?
|
|
#Wenig Daten erforderlich
|
|
#Versatile einsetzbar
|
|
#Training nicht auf Endgerät, jedoch auf anderem
|
|
#Keine Objekte notwendig
|
|
#TODO: eval anzahl an grundbildern - augmentierte extra bilder
|
|
|
|
#TODO Das andere model testen
|
|
|
|
|
|
#TODO ich glaube wirklich, dass man lieber patch/kanal-weise analysieren muss. Eine globale betrachtung verfälscht zu stark.
|
|
#Also erster Schritt, man prüft den neuen modelltypen.
|
|
#Wie kann ich dafür sorgen, dass ich sinnvoll jeden bereich convolve? DWS?
|
|
#Zweiter Schritt. Man prüft den neuen Datensatz mit den Objekten aus MINC
|
|
|
|
|
|
#TODO: die gleich bilder augmentieren mit objekten
|
|
#TODO: die bilder mit materialien augmentieren, aber vllt mehr bilder
|
|
|
|
|
|
#TODO: Data augmentation, vllt einfach schwarze objekte? oder größer?
|
|
#TODO: oder einfach objekte aus dem MINC dataset projezieren?
|
|
|
|
#TODO: Klassifiziere jeden Patch separat, Channel-wise FC für jeden Patch
|
|
# Dann FC Layer, um die Ergebnisse zusammenzuführen
|
|
|
|
if __name__ == '__main__':
|
|
mySeed = 42
|
|
reset_random_seeds(mySeed)
|
|
# 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
|
|
dataset_path = "C:/Users/bijan/Desktop/efficient_surface_anomaly_detector/data/dataset_for_paper/"
|
|
|
|
# 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.")
|
|
|
|
n_test_images_per_class = 1000
|
|
|
|
grayscales = [True]
|
|
learning_rates = [0.001]
|
|
|
|
train_val_ratios = [0.5] #[0.3, 0.5, 0.7]
|
|
n_train_val_images_per_class_list = [10]
|
|
target_image_sizes = [256]
|
|
n_tiles_per_side_list = [4, 8, 16, 32]
|
|
|
|
output_channels_ds_conv_list = [8, 16, 32, 64, 128]
|
|
kernel_sizes = [3, 5, 7, 9]
|
|
num_conv_layers_list = [1, 2, 3]
|
|
num_fc_layers_list = [1, 2, 3]
|
|
hidden_units_list = [16, 32, 64, 128]
|
|
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]
|
|
with_shuffle_channels_list = [False] #[True, False]
|
|
with_rotate_channels_list = [False] #[True, False]
|
|
|
|
num_experiments = (len(train_val_ratios) * len(grayscales) * len(learning_rates) *
|
|
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(num_conv_layers_list) * len(num_fc_layers_list) *
|
|
len(with_shuffle_channels_list) * len(with_rotate_channels_list) *
|
|
len(hidden_units_list) * len(dropout_rates))
|
|
progress_counter = 0
|
|
|
|
for grayscale in grayscales:
|
|
for train_val_ratio in train_val_ratios:
|
|
for learning_rate in learning_rates:
|
|
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:
|
|
reset_random_seeds(mySeed)
|
|
gc.collect()
|
|
torch.cuda.empty_cache()
|
|
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,
|
|
dataset_path=dataset_path
|
|
)
|
|
|
|
data_parameters = (f"gray_{grayscale}_tvr_{train_val_ratio}_"
|
|
f"lr_{learning_rate}_ntvimg_{n_train_val_images_per_class}_"
|
|
f"imgsz_{target_image_size}_ntiles_{n_tiles_per_side}")
|
|
|
|
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 num_conv_layers in num_conv_layers_list:
|
|
for num_fc_layers in num_fc_layers_list:
|
|
for hidden_units in hidden_units_list:
|
|
for dropout_rate in dropout_rates:
|
|
for with_shuffle_channels in with_shuffle_channels_list:
|
|
for with_rotate_channels in with_rotate_channels_list:
|
|
# Construct a unique identifier for this experiment
|
|
configuration_name = (f"{data_parameters}_oc_{output_channels_ds_conv}_"
|
|
f"ks_{kernel_size}_ncl_{num_conv_layers}_nhl_{num_fc_layers}_"
|
|
f"shuffle_{with_shuffle_channels}_rotate_{with_rotate_channels}_"
|
|
f"hu_{hidden_units}_dr_{dropout_rate}")
|
|
|
|
# If the experiment has been completed already, skip it.
|
|
if configuration_name in completed_experiments:
|
|
print(f"Skipping completed experiment: {configuration_name}")
|
|
progress_counter += 1
|
|
continue
|
|
reset_random_seeds(mySeed)
|
|
gc.collect()
|
|
torch.cuda.empty_cache()
|
|
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,
|
|
num_conv_layers=num_conv_layers,
|
|
num_fc_layers=num_fc_layers,
|
|
hidden_units=hidden_units,
|
|
dropout_rate=dropout_rate,
|
|
with_shuffle_channels=with_shuffle_channels,
|
|
with_rotate_channels=with_rotate_channels,
|
|
learning_rate=learning_rate,
|
|
epochs=epochs,
|
|
batch_size=batch_size,
|
|
model_save_path=model_save_path,
|
|
log_path=log_path,
|
|
configuration_name=configuration_name
|
|
)
|
|
|
|
# Save the experiment id to the checkpoint file immediately after completion
|
|
with open(checkpoint_file, "a") as f:
|
|
f.write(configuration_name + "\n")
|
|
completed_experiments.add(configuration_name)
|
|
|
|
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()
|
|
reset_random_seeds(mySeed)
|
|
gc.collect()
|
|
torch.cuda.empty_cache()
|
|
print("Deleting current datasets...")
|
|
del X_train, y_train, X_val, y_val, X_test, y_test
|
|
reset_random_seeds(mySeed)
|
|
gc.collect()
|
|
torch.cuda.empty_cache()
|