367 lines
15 KiB
Python
367 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
|
|
|
|
# --- 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")
|
|
|
|
|
|
# --- Data Preparation Functions ---
|
|
|
|
def load_and_grayscale(image_path):
|
|
# Open image and convert to grayscale (mode 'L')
|
|
img = Image.open(image_path).convert('L')
|
|
return np.array(img)
|
|
|
|
def pad_image_and_resize(img_array, target_size):
|
|
h, w = img_array.shape[:2]
|
|
max_side = max(h, w)
|
|
delta_w = max_side - w
|
|
delta_h = max_side - h
|
|
top, bottom = delta_h // 2, delta_h - delta_h // 2
|
|
left, right = delta_w // 2, delta_w - delta_w // 2
|
|
pad_width = ((top, bottom), (left, right))
|
|
img_padded = np.pad(img_array, pad_width, mode='constant', constant_values=0)
|
|
img_resized = cv2.resize(img_padded, (target_size, target_size), interpolation=cv2.INTER_AREA)
|
|
return img_resized
|
|
|
|
def tile_and_stack(image, num_tiles_per_side):
|
|
# Assumes a square image.
|
|
tile_size = image.shape[0] // num_tiles_per_side
|
|
tiles = []
|
|
for i in range(num_tiles_per_side):
|
|
for j in range(num_tiles_per_side):
|
|
tile = image[
|
|
i * tile_size:(i + 1) * tile_size,
|
|
j * tile_size:(j + 1) * tile_size
|
|
]
|
|
tiles.append(tile)
|
|
stacked_image = np.stack(tiles, axis=0) # shape: (num_tiles, tile_size, tile_size)
|
|
return stacked_image
|
|
|
|
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
|
|
|
|
|
|
# --- PyTorch Model Definition ---
|
|
class ForeignObjectClassificationModel(nn.Module):
|
|
def __init__(self, input_channels, output_channels_ds_conv, kernel_size, hidden_units, dropout_rate):
|
|
super(ForeignObjectClassificationModel, self).__init__()
|
|
# Depthwise convolution: set groups=input_channels so that each channel is convolved separately.
|
|
self.depthwise = nn.Conv2d(
|
|
in_channels=input_channels,
|
|
out_channels=input_channels,
|
|
kernel_size=kernel_size,
|
|
padding=kernel_size // 2,
|
|
groups=input_channels
|
|
)
|
|
self.relu = nn.ReLU()
|
|
# Pointwise convolution (1x1 conv)
|
|
self.pointwise = nn.Conv2d(
|
|
in_channels=input_channels,
|
|
out_channels=output_channels_ds_conv,
|
|
kernel_size=1
|
|
)
|
|
# Global average pooling to output (batch, channels, 1, 1)
|
|
self.global_avg_pool = nn.AdaptiveAvgPool2d(1)
|
|
# Fully connected layers
|
|
self.fc1 = nn.Linear(output_channels_ds_conv, hidden_units)
|
|
self.dropout = nn.Dropout(dropout_rate)
|
|
self.fc2 = nn.Linear(hidden_units, 1)
|
|
self.sigmoid = nn.Sigmoid()
|
|
|
|
def forward(self, x):
|
|
x = self.relu(self.depthwise(x))
|
|
x = self.relu(self.pointwise(x))
|
|
x = self.global_avg_pool(x)
|
|
x = x.view(x.size(0), -1) # flatten (batch, channels)
|
|
x = self.relu(self.fc1(x))
|
|
x = self.dropout(x)
|
|
x = self.sigmoid(self.fc2(x))
|
|
return x
|
|
|
|
|
|
# --- Training, Validation, and Evaluation Functions ---
|
|
|
|
def train_and_validate(model, optimizer, criterion, train_loader, val_loader, epochs, patience, device):
|
|
best_val_acc = 0.0
|
|
best_model_state = None
|
|
train_acc_history = []
|
|
val_acc_history = []
|
|
patience_counter = 0
|
|
|
|
for epoch in range(epochs):
|
|
model.train()
|
|
train_loss = 0.0
|
|
train_correct = 0
|
|
train_total = 0
|
|
|
|
for inputs, targets in train_loader:
|
|
inputs = inputs.to(device)
|
|
targets = targets.to(device).float() # ensure float type for BCELoss
|
|
optimizer.zero_grad()
|
|
outputs = model(inputs)
|
|
loss = criterion(outputs, targets.unsqueeze(1))
|
|
loss.backward()
|
|
optimizer.step()
|
|
train_loss += loss.item() * inputs.size(0)
|
|
# Compute binary predictions (threshold=0.5)
|
|
preds = (outputs > 0.5).float()
|
|
train_correct += (preds.squeeze(1) == targets).sum().item()
|
|
train_total += targets.size(0)
|
|
|
|
train_acc = train_correct / train_total if train_total > 0 else 0
|
|
train_acc_history.append(train_acc)
|
|
|
|
model.eval()
|
|
val_loss = 0.0
|
|
val_correct = 0
|
|
val_total = 0
|
|
with torch.no_grad():
|
|
for inputs, targets in val_loader:
|
|
inputs = inputs.to(device)
|
|
targets = targets.to(device).float()
|
|
outputs = model(inputs)
|
|
loss = criterion(outputs, targets.unsqueeze(1))
|
|
val_loss += loss.item() * inputs.size(0)
|
|
preds = (outputs > 0.5).float()
|
|
val_correct += (preds.squeeze(1) == targets).sum().item()
|
|
val_total += targets.size(0)
|
|
val_acc = val_correct / val_total if val_total > 0 else 0
|
|
val_acc_history.append(val_acc)
|
|
|
|
print(f"Epoch {epoch+1}/{epochs} | Train Acc: {train_acc:.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)
|
|
|
|
history = {
|
|
'binary_accuracy': train_acc_history,
|
|
'val_binary_accuracy': val_acc_history
|
|
}
|
|
return history
|
|
|
|
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)
|
|
avg_loss = test_loss / test_total if test_total > 0 else 0
|
|
test_acc = test_correct / test_total if test_total > 0 else 0
|
|
return avg_loss, test_acc
|
|
|
|
|
|
# --- Experiment Pipeline ---
|
|
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...")
|
|
history = train_and_validate(model, optimizer, criterion,
|
|
train_loader, val_loader,
|
|
epochs=epochs, patience=100, device=self.device)
|
|
|
|
best_val_acc = max(history['val_binary_accuracy'])
|
|
best_train_acc = max(history['binary_accuracy'])
|
|
print(f"Best validation accuracy: {best_val_acc:.4f}")
|
|
|
|
print("Running evaluation on test set...")
|
|
test_loss, 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}_train_{best_train_acc:.4f}_val_{best_val_acc:.4f}_test_{test_acc:.4f}.pt")
|
|
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 f:
|
|
f.write(f"Model: {model_name}, Train Accuracy: {best_train_acc:.4f}, "
|
|
f"Validation Accuracy: {best_val_acc:.4f}, Test Accuracy: {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)
|
|
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
|
|
|
|
|
|
# --- Main Execution ---
|
|
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 = "" # path to your images
|
|
model_save_path = "" # path to save the model
|
|
log_path = "" # path to save the logs
|
|
|
|
train_val_ratio = 0.5
|
|
n_test_images_per_class = 1000
|
|
|
|
n_train_val_images_per_class_list = [100] # e.g. [1,2,3,...]
|
|
target_image_sizes = [256] # e.g. [32, 64, 128, 256]
|
|
n_tiles_per_side_list = [8] # e.g. [2, 4, 8, 16]
|
|
|
|
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 = 1
|
|
|
|
output_channels_ds_conv_list = [16] # e.g. [8, 16, 32, 64]
|
|
|