Added second model and second experiment pipeline, while running other experiments
This commit is contained in:
+90
-36
@@ -198,8 +198,19 @@ class ExperimentPipeline:
|
||||
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):
|
||||
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)
|
||||
@@ -210,42 +221,60 @@ def create_train_val_test_sets(image_folder, n_train_val_images_per_class, train
|
||||
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]
|
||||
print(" dataset_path:", dataset_path)
|
||||
|
||||
# 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]
|
||||
X_train = None
|
||||
y_train = None
|
||||
X_val = None
|
||||
y_val = None
|
||||
X_test = None
|
||||
y_test = None
|
||||
|
||||
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!")
|
||||
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]
|
||||
|
||||
# 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]
|
||||
# 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]
|
||||
|
||||
# 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)
|
||||
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!")
|
||||
|
||||
# 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
|
||||
# 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]
|
||||
|
||||
# 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)
|
||||
# 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))
|
||||
@@ -264,9 +293,32 @@ def reset_random_seeds(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: Klassifiziere jeden Patch separat
|
||||
# DWS-Conv, und dann FC layer auf jedem Patch
|
||||
#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__':
|
||||
@@ -276,6 +328,7 @@ if __name__ == '__main__':
|
||||
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:
|
||||
@@ -300,7 +353,7 @@ if __name__ == '__main__':
|
||||
|
||||
train_val_ratios = [0.5] #[0.3, 0.5, 0.7]
|
||||
n_train_val_images_per_class_list = [10]
|
||||
target_image_sizes = [128]#, 256]
|
||||
target_image_sizes = [256]
|
||||
n_tiles_per_side_list = [4, 8, 16, 32]
|
||||
|
||||
output_channels_ds_conv_list = [8, 16, 32, 64, 128]
|
||||
@@ -309,7 +362,7 @@ if __name__ == '__main__':
|
||||
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 = [True, False]
|
||||
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) *
|
||||
@@ -336,7 +389,8 @@ if __name__ == '__main__':
|
||||
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
|
||||
grayscale=grayscale,
|
||||
dataset_path=dataset_path
|
||||
)
|
||||
|
||||
data_parameters = (f"gray_{grayscale}_tvr_{train_val_ratio}_"
|
||||
|
||||
+394
@@ -0,0 +1,394 @@
|
||||
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
|
||||
|
||||
from model2 import ForeignObjectClassificationModel2
|
||||
|
||||
# --- 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, target_image_sizes, kernel_size, num_conv_layers, patch_hidden_units, merge_hidden_units,
|
||||
dropout_rate_input, dropout_rate_patch_classifier, dropout_rate_merge,
|
||||
learning_rate, epochs, batch_size, model_save_path, log_path, configuration_name):
|
||||
print(f"Running experiment for {configuration_name}")
|
||||
# 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 = ForeignObjectClassificationModel2(
|
||||
input_channels=input_channels, # Here, input_channels equals the number of patches (e.g., 32)
|
||||
patch_size=input_shape[1], # or input_shape[2],
|
||||
kernel_size=kernel_size,
|
||||
num_conv_layers=num_conv_layers, # number of convolutional layers (operating on each patch independently)
|
||||
patch_classifier_hidden_units=patch_hidden_units, # hidden units for patch classifier MLP
|
||||
dropout_rate_input=dropout_rate_input,
|
||||
dropout_rate_patch_classifier=dropout_rate_patch_classifier,
|
||||
merge_hidden_units=merge_hidden_units, # hidden units for patch merger MLP
|
||||
dropout_rate_merge=dropout_rate_merge)
|
||||
|
||||
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(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(" 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 not dataset_path:
|
||||
raise ValueError("Dataset path not provided.")
|
||||
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)
|
||||
|
||||
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
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
mySeed = 42
|
||||
reset_random_seeds(mySeed)
|
||||
# Update these paths as needed
|
||||
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/log2/" # 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.")
|
||||
|
||||
grayscales = [True]
|
||||
learning_rates = [0.001]
|
||||
batch_sizes = [10]
|
||||
train_val_ratios = [0.5] #[0.3, 0.5, 0.7]
|
||||
|
||||
target_image_sizes = [256]
|
||||
n_tiles_per_side_list = [4, 8, 16, 32]
|
||||
|
||||
kernel_sizes = [3, 5, 7, 9]
|
||||
num_conv_layers_list = [1, 2, 3]
|
||||
|
||||
patch_hidden_units_list = [16, 32, 64, 128]
|
||||
merge_hidden_units_list= [16, 32, 64, 128]
|
||||
dropout_rate_input_list = [0, 0.25, 0.5, 0.75]
|
||||
dropout_rate_patch_classifier_list = [0, 0.25, 0.5, 0.75]
|
||||
dropout_rate_merge_list= [0, 0.25, 0.5, 0.75]
|
||||
|
||||
|
||||
num_experiments = (len(train_val_ratios) * len(grayscales) * len(batch_sizes) *
|
||||
len(learning_rates) * len(target_image_sizes) *
|
||||
len(n_tiles_per_side_list) *
|
||||
len(kernel_sizes) * len(num_conv_layers_list) *
|
||||
len(patch_hidden_units_list) * len(merge_hidden_units_list) *
|
||||
len(dropout_rate_input_list) * len(dropout_rate_patch_classifier_list) *
|
||||
len(dropout_rate_merge_list))
|
||||
progress_counter = 0
|
||||
|
||||
for train_val_ratio in train_val_ratios:
|
||||
for grayscale in grayscales:
|
||||
for batch_size in batch_sizes:
|
||||
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 = 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"train_val_ratio_{train_val_ratio}_"
|
||||
f"gray_{grayscale}_"
|
||||
f"bs_{batch_size}_"
|
||||
f"lr_{learning_rate}_"
|
||||
f"imgsz_{target_image_size}_"
|
||||
f"ntiles_{n_tiles_per_side}")
|
||||
|
||||
epochs = 1000
|
||||
for kernel_size in kernel_sizes:
|
||||
for num_conv_layers in num_conv_layers_list:
|
||||
for patch_hidden_units in patch_hidden_units_list:
|
||||
for merge_hidden_units in merge_hidden_units_list:
|
||||
for dropout_rate_input in dropout_rate_input_list:
|
||||
for dropout_rate_patch_classifier in dropout_rate_patch_classifier_list:
|
||||
for dropout_rate_merge in dropout_rate_merge_list:
|
||||
# Construct a unique identifier for this experiment
|
||||
configuration_name = (f"{data_parameters}_"
|
||||
f"ks_{kernel_size}_"
|
||||
f"ncl_{num_conv_layers}_"
|
||||
f"phu_{patch_hidden_units}_"
|
||||
f"mhu_{merge_hidden_units}_"
|
||||
f"drinput_{dropout_rate_input}_"
|
||||
f"drpc_{dropout_rate_patch_classifier}_"
|
||||
f"drmerge_{dropout_rate_merge}")
|
||||
|
||||
# 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(
|
||||
target_image_sizes=target_image_sizes,
|
||||
kernel_size=kernel_size,
|
||||
num_conv_layers=num_conv_layers,
|
||||
patch_hidden_units=patch_hidden_units,
|
||||
merge_hidden_units=merge_hidden_units,
|
||||
dropout_rate_input=dropout_rate_input,
|
||||
dropout_rate_patch_classifier=dropout_rate_patch_classifier,
|
||||
dropout_rate_merge=dropout_rate_merge,
|
||||
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()
|
||||
+4
-3
@@ -29,14 +29,14 @@ class RandomChannelRotation(nn.Module):
|
||||
return out
|
||||
|
||||
class DepthWiseSeperableConv(nn.Module):
|
||||
def __init__(self, in_channels, out_channels, kernel_size):
|
||||
def __init__(self, in_channels, out_channels, kernel_size, padding):
|
||||
super(DepthWiseSeperableConv, self).__init__()
|
||||
# Depthwise convolution (each channel is convolved separately)
|
||||
self.depthwise = nn.Conv2d(
|
||||
in_channels=in_channels,
|
||||
out_channels=in_channels,
|
||||
kernel_size=kernel_size,
|
||||
padding=kernel_size // 2,
|
||||
padding=padding,
|
||||
groups=in_channels
|
||||
)
|
||||
self.batch_norm_depth = nn.BatchNorm2d(in_channels)
|
||||
@@ -89,7 +89,8 @@ class ForeignObjectClassificationModel(nn.Module):
|
||||
conv_layers = []
|
||||
for i in range(num_conv_layers):
|
||||
in_ch = input_channels if i == 0 else conv_out_channels
|
||||
conv_layers.append(DepthWiseSeperableConv(in_ch, conv_out_channels, kernel_size))
|
||||
padding = kernel_size // 2
|
||||
conv_layers.append(DepthWiseSeperableConv(in_ch, conv_out_channels, kernel_size, padding))
|
||||
self.dws_conv_layers = nn.Sequential(*conv_layers)
|
||||
|
||||
# Global average pooling to reduce spatial dimensions.
|
||||
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
class DepthWiseSeperableConv(nn.Module):
|
||||
def __init__(self, in_channels, out_channels, kernel_size, padding):
|
||||
super(DepthWiseSeperableConv, self).__init__()
|
||||
# Depthwise convolution: each channel is convolved separately.
|
||||
self.depthwise = nn.Conv2d(
|
||||
in_channels=in_channels,
|
||||
out_channels=in_channels,
|
||||
kernel_size=kernel_size,
|
||||
padding=padding,
|
||||
groups=in_channels
|
||||
)
|
||||
self.batch_norm_depth = nn.BatchNorm2d(in_channels)
|
||||
self.relu = nn.ReLU()
|
||||
# Pointwise convolution (mixes the channels)
|
||||
self.pointwise = nn.Conv2d(
|
||||
in_channels=in_channels,
|
||||
out_channels=out_channels,
|
||||
kernel_size=1
|
||||
)
|
||||
self.batch_norm_pointwise = nn.BatchNorm2d(out_channels)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.depthwise(x)
|
||||
x = self.batch_norm_depth(x)
|
||||
x = self.relu(x)
|
||||
x = self.pointwise(x)
|
||||
x = self.batch_norm_pointwise(x)
|
||||
x = self.relu(x)
|
||||
return x
|
||||
|
||||
class PatchClassifier(nn.Module):
|
||||
"""
|
||||
A small MLP that classifies each patch.
|
||||
Each patch is first flattened from its [patch_H, patch_W] spatial dimensions into a feature vector.
|
||||
In your assumed setting, the input already has shape [B, num_patches, patch_H, patch_W],
|
||||
for example [10, 32, 32, 32] where the 32 channels represent 32 pre-divided patches.
|
||||
This classifier outputs one scalar per patch.
|
||||
"""
|
||||
def __init__(self, in_features, hidden_units, dropout_rate):
|
||||
super(PatchClassifier, self).__init__()
|
||||
self.fc1 = nn.Linear(in_features, hidden_units)
|
||||
self.relu = nn.ReLU()
|
||||
self.dropout = nn.Dropout(dropout_rate)
|
||||
self.fc2 = nn.Linear(hidden_units, 1)
|
||||
|
||||
def forward(self, x):
|
||||
# x shape: [B, num_patches, in_features]
|
||||
x = self.fc1(x)
|
||||
x = self.relu(x)
|
||||
x = self.dropout(x)
|
||||
x = self.fc2(x)
|
||||
return x # Output shape: [B, num_patches, 1]
|
||||
|
||||
class PatchMerger(nn.Module):
|
||||
def __init__(self, num_patches, merge_hidden_units, dropout_rate):
|
||||
super(PatchMerger, self).__init__()
|
||||
self.mlp = nn.Sequential(
|
||||
nn.Linear(num_patches, merge_hidden_units),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(dropout_rate),
|
||||
nn.Linear(merge_hidden_units, 1)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
# x is expected to be [B, num_patches, 1]. For example, [10, 32, 1].
|
||||
# Flatten it to [B, num_patches]:
|
||||
x = x.view(x.size(0), -1)
|
||||
out = self.mlp(x)
|
||||
return torch.sigmoid(out) # Final output shape is [B, 1]
|
||||
|
||||
|
||||
|
||||
class ForeignObjectClassificationModel2(nn.Module):
|
||||
def __init__(self,
|
||||
input_channels, # Here, input_channels equals the number of patches (e.g., 32)
|
||||
patch_size,
|
||||
kernel_size,
|
||||
num_conv_layers, # number of convolutional layers (operating on each patch independently)
|
||||
patch_classifier_hidden_units, # hidden units for patch classifier MLP
|
||||
dropout_rate_input,
|
||||
dropout_rate_patch_classifier,
|
||||
merge_hidden_units, # hidden units for patch merger MLP
|
||||
dropout_rate_merge):
|
||||
super(ForeignObjectClassificationModel2, self).__init__()
|
||||
|
||||
self.dropout_input = nn.Dropout(dropout_rate_input)
|
||||
|
||||
# Build convolutional blocks that process each patch independently.
|
||||
conv_layers = []
|
||||
for i in range(num_conv_layers):
|
||||
padding = kernel_size // 2
|
||||
# Here, we keep the number of channels constant since the channels represent individual patches.
|
||||
conv_layers.append(DepthWiseSeperableConv(input_channels, input_channels, kernel_size, padding))
|
||||
self.conv_layers = nn.Sequential(*conv_layers)
|
||||
|
||||
# Assume each patch is of size 32x32.
|
||||
in_features_patch = patch_size * patch_size # e.g., 32*32 = 1024
|
||||
|
||||
# Patch classifier: processes each patch (flattened to a vector of length 1024).
|
||||
self.patch_classifier = PatchClassifier(in_features=in_features_patch,
|
||||
hidden_units=patch_classifier_hidden_units,
|
||||
dropout_rate=dropout_rate_patch_classifier)
|
||||
# Patch merger: aggregates the patch-level predictions with learnable parameters.
|
||||
self.patch_merger = PatchMerger(input_channels, merge_hidden_units, dropout_rate_merge)
|
||||
|
||||
def forward(self, x):
|
||||
# print(x.shape)
|
||||
# x shape: [B, num_patches, patch_H, patch_W]
|
||||
# e.g., [10, 32, 32, 32] -- 32 patches already provided as channels.
|
||||
x = self.dropout_input(x)
|
||||
# Apply convolutional layers.
|
||||
# Note: The conv layers are applied per patch (channel) without mixing patch identities.
|
||||
x = self.conv_layers(x) # Shape remains [B, num_patches, patch_H, patch_W].
|
||||
# print(x.shape)
|
||||
B, num_patches, H, W = x.shape # Here, num_patches should equal input_channels (e.g., 32)
|
||||
# Flatten each patch's spatial dimensions.
|
||||
patches = x.view(B, num_patches, -1) # shape: [B, num_patches, H*W]. With H=W=32, in_features = 1024.
|
||||
# print(patches.shape)
|
||||
# Apply the patch classifier to each patch.
|
||||
patch_preds = self.patch_classifier(patches) # Expected shape: [B, num_patches, 1]
|
||||
# print(patch_preds.shape)
|
||||
# Merge patch predictions with the learnable PatchMerger.
|
||||
final_preds = self.patch_merger(patch_preds) # shape: [B, 1]
|
||||
# print(final_preds.shape)
|
||||
return final_preds
|
||||
|
||||
# # Example usage:
|
||||
# if __name__ == '__main__':
|
||||
# # Assume the input is already divided into patches:
|
||||
# # For a batch of 10 samples, we have 32 patches per sample, and each patch is 32x32.
|
||||
# dummy_input = torch.randn(10, 32, 32, 32) # [B, num_patches, patch_H, patch_W]
|
||||
# model = ForeignObjectClassificationModel2(
|
||||
# patch_size=32,
|
||||
# input_channels=32, # 32 patches provided (in the channel dimension)
|
||||
# kernel_size=3,
|
||||
# num_conv_layers=3, # Number of convolutional layers
|
||||
# patch_classifier_hidden_units=64, # Hidden units in patch classifier MLP
|
||||
# dropout_rate_input=0.5,
|
||||
# dropout_rate_patch_classifier=0.5,
|
||||
# merge_hidden_units=32, # Hidden units in patch merger MLP
|
||||
# dropout_rate_merge=0.5
|
||||
# )
|
||||
# output = model(dummy_input)
|
||||
# print("Output shape:", output.shape) # Expected: [10, 1]
|
||||
Reference in New Issue
Block a user