421 lines
20 KiB
Python
421 lines
20 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 = "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(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))
|
|
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
|
|
|
|
total_train_samples = len(train_loader.dataset)
|
|
|
|
for epoch in range(epochs):
|
|
model.train()
|
|
running_loss = 0.0
|
|
num_batches = len(train_loader)
|
|
|
|
for i, (tile_images, labels) in enumerate(train_loader, start=1):
|
|
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()
|
|
running_loss += loss.item() * tile_images.size(0)
|
|
|
|
# # Print progress every 10% of batches processed, or for the last batch.
|
|
# if i % max(1, num_batches // 10) == 0 or i == num_batches:
|
|
# print(f" Batch {i}/{num_batches} processed.")
|
|
|
|
average_train_loss = running_loss / total_train_samples
|
|
|
|
# Validate the model.
|
|
model.eval()
|
|
with torch.no_grad():
|
|
val_acc = evaluate(model, val_loader, criterion, device)
|
|
print(f"\nEpoch {epoch+1}/{epochs} Training Loss: {average_train_loss:.4f} Validation Accuracy: {val_acc:.4f}")
|
|
|
|
# Check for improvement.
|
|
if val_acc > best_val_acc:
|
|
best_val_acc = val_acc
|
|
best_model_state = model.state_dict()
|
|
patience_counter = 0
|
|
print("New best model found!")
|
|
else:
|
|
patience_counter += 1
|
|
print(f"No improvement. Patience counter: {patience_counter}/{patience}")
|
|
|
|
# Early stopping.
|
|
if patience_counter >= patience:
|
|
print(f"Early stopping triggered 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
|
|
|
|
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
|
|
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))
|
|
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
|
|
|
|
# -------------------------------
|
|
def create_train_val_test_sets(target_image_size, num_tiles_per_side, grayscale, dataset_path):
|
|
print("Data preparation with parameters:")
|
|
print(" target_image_size:", target_image_size)
|
|
print(" num_tiles_per_side:", num_tiles_per_side)
|
|
print(" grayscale:", grayscale)
|
|
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, num_tiles_per_side, grayscale)
|
|
X_val, y_val = load_dataset(val_files, val_labels, target_image_size, num_tiles_per_side, grayscale)
|
|
|
|
# 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, num_tiles_per_side, grayscale)
|
|
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(val) for key, val 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, base_conv_channels, kernel_size, num_conv_layers, num_fc_layers,
|
|
hidden_units, pooling_after_each_conv, conv_pooling_type, global_pooling_type,
|
|
learning_rate, epochs, batch_size, model_save_path, log_path, configuration_name):
|
|
print(f"Running experiment for {configuration_name}, "
|
|
f"base_conv_channels={base_conv_channels}, kernel_size={kernel_size}, "
|
|
f"hidden_units={hidden_units}, learning_rate={learning_rate}, epochs={epochs}, "
|
|
f"batch_size={batch_size}, model_save_path={model_save_path}, log_path={log_path}")
|
|
|
|
input_shape = self.X_train.shape[1:]
|
|
print("Model input shape:", input_shape)
|
|
input_channels = input_shape[0]
|
|
|
|
model = ForeignObjectClassificationModel(
|
|
input_channels=input_channels,
|
|
base_conv_channels=base_conv_channels,
|
|
kernel_size=kernel_size,
|
|
num_conv_layers=num_conv_layers,
|
|
num_fc_layers=num_fc_layers,
|
|
hidden_units=hidden_units,
|
|
pooling_after_each_conv=pooling_after_each_conv,
|
|
conv_pooling_type=conv_pooling_type,
|
|
global_pooling_type=global_pooling_type
|
|
)
|
|
model.to(self.device)
|
|
|
|
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
|
criterion = nn.BCELoss()
|
|
|
|
# Create DataLoaders for training and validation.
|
|
train_dataset = TensorDataset(self.X_train, self.y_train)
|
|
val_dataset = TensorDataset(self.X_val, self.y_val)
|
|
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
|
|
val_loader = DataLoader(val_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=50, device=self.device)
|
|
print(f"Best validation accuracy: {best_val_acc:.4f}")
|
|
|
|
# Global test evaluation.
|
|
if self.X_test_global is not None:
|
|
print("Running global test evaluation...")
|
|
global_test_dataset = TensorDataset(self.X_test_global, self.y_test_global)
|
|
global_test_loader = DataLoader(global_test_dataset, batch_size=batch_size, shuffle=False)
|
|
global_test_acc = evaluate(model, global_test_loader, criterion, self.device)
|
|
print(f"Global Test accuracy: {global_test_acc:.4f}")
|
|
else:
|
|
global_test_acc = None
|
|
print("Global Test set is empty.")
|
|
|
|
# Evaluation for each test subfolder.
|
|
per_subfolder_acc = {}
|
|
print("Running per-subfolder test evaluations...")
|
|
for subfolder, X_sub in self.X_test_dict.items():
|
|
y_sub = self.y_test_dict[subfolder]
|
|
if X_sub.size(0) == 0:
|
|
print(f"Subfolder '{subfolder}' has no samples. Skipping evaluation.")
|
|
per_subfolder_acc[subfolder] = None
|
|
continue
|
|
|
|
sub_dataset = TensorDataset(X_sub, y_sub)
|
|
sub_loader = DataLoader(sub_dataset, batch_size=batch_size, shuffle=False)
|
|
sub_acc = evaluate(model, sub_loader, criterion, self.device)
|
|
per_subfolder_acc[subfolder] = sub_acc
|
|
print(f"Test accuracy for '{subfolder}': {sub_acc:.4f}")
|
|
|
|
# Save the model
|
|
model_name = f"{configuration_name}_val_{best_val_acc:.4f}_global_test_{global_test_acc:.4f}.pt"
|
|
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}, {best_val_acc:.4f}, {global_test_acc}, {per_subfolder_acc}\n")
|
|
print(f'Model trained, evaluated and saved as {model_name}')
|
|
|
|
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_394_no_conv_pool_rotated_blurred_objects_3_sizes_brightness_64" # 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: template network?
|
|
#TODO: YOLO NUTZEN!
|
|
#TODO: Andere augmentierung mit random objekten aus segment dataset
|
|
#TODO: Metallerkennung
|
|
|
|
epochs = 1000
|
|
batch_size = 512 # 128?
|
|
grayscales = [True]
|
|
pooling_after_each_conv_list = [False]#, False]
|
|
conv_pooling_type_list = ["max"] #['max', 'avg']
|
|
global_pooling_type_list = ["avg"] #['max', 'avg']
|
|
learning_rates = [0.001]
|
|
target_image_sizes = [394] #standard should be 394
|
|
n_tiles_per_side_list = [64] # [8, 16, 32, 64]
|
|
base_channels_ds_conv_list = [16, 32, 64, 128] #[128, 64, 32, 16] #["double_input"] #[32, 64, 128]
|
|
kernel_sizes = [3, 5, 7, 9]
|
|
num_conv_layers_list = [1, 2, 3]#[3, 2, 1]
|
|
num_fc_layers_list = [1, 2, 3]#[3, 2, 1]
|
|
hidden_units_list = [16, 32, 64, 128, 256]#[128, 64, 32, 16]
|
|
|
|
num_experiments = (len(grayscales) * len(learning_rates) * len(target_image_sizes) *
|
|
len(pooling_after_each_conv_list) * len(conv_pooling_type_list) *
|
|
len(global_pooling_type_list) * len(n_tiles_per_side_list) *
|
|
len(base_channels_ds_conv_list) * len(kernel_sizes) *
|
|
len(num_conv_layers_list) * len(num_fc_layers_list) *
|
|
len(hidden_units_list))
|
|
progress_counter = 0
|
|
|
|
for grayscale in grayscales:
|
|
for learning_rate in learning_rates:
|
|
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, X_test_dict, y_test_dict = create_train_val_test_sets(
|
|
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}_lr_{learning_rate}_"
|
|
f"imgsz_{target_image_size}_ntiles_{n_tiles_per_side}")
|
|
for base_channels_ds_conv in base_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 pooling_after_each_conv in pooling_after_each_conv_list:
|
|
for conv_pooling_type in conv_pooling_type_list:
|
|
for global_pooling_type in global_pooling_type_list:
|
|
configuration_name = (f"{data_parameters}_oc_{base_channels_ds_conv}_"
|
|
f"ks_{kernel_size}_ncl_{num_conv_layers}_nhl_{num_fc_layers}_"
|
|
f"hu_{hidden_units}_pool_conv_{pooling_after_each_conv}_"
|
|
f"conv_pool_type_{conv_pooling_type}_global_pool_type_{global_pooling_type}")
|
|
if configuration_name in completed_experiments:
|
|
print(f"Skipping: {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, X_test_dict, y_test_dict,
|
|
device=device
|
|
)
|
|
experiment_pipeline.run_full_experiment(
|
|
base_conv_channels=base_channels_ds_conv,
|
|
kernel_size=kernel_size,
|
|
num_conv_layers=num_conv_layers,
|
|
num_fc_layers=num_fc_layers,
|
|
hidden_units=hidden_units,
|
|
pooling_after_each_conv=pooling_after_each_conv,
|
|
conv_pooling_type=conv_pooling_type,
|
|
global_pooling_type=global_pooling_type,
|
|
learning_rate=learning_rate,
|
|
epochs=epochs,
|
|
batch_size=batch_size,
|
|
model_save_path=model_save_path,
|
|
log_path=log_path,
|
|
configuration_name=configuration_name
|
|
)
|
|
with open(checkpoint_file, "a") as f:
|
|
f.write(configuration_name + "\n")
|
|
completed_experiments.add(configuration_name)
|
|
progress_counter += 1
|
|
print(f"Progress: {progress_counter}/{num_experiments} ({(progress_counter / num_experiments * 100):.2f}%)")
|
|
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, X_test_dict, y_test_dict
|
|
reset_random_seeds(mySeed)
|
|
gc.collect()
|
|
torch.cuda.empty_cache()
|
|
|
|
if __name__ == '__main__':
|
|
main()
|