commit a985ea370b55964ccb6cf38d5451df0bec8f6f94 Author: BIJAN_G16\bijan Date: Fri Mar 21 13:57:02 2025 +0100 initial commit with some unfinished code diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6fcceb4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +data/* +code/.idea/* \ No newline at end of file diff --git a/code/data_adapter.py b/code/data_adapter.py new file mode 100644 index 0000000..45f00a9 --- /dev/null +++ b/code/data_adapter.py @@ -0,0 +1,27 @@ +from PIL import Image, ImageOps +import numpy as np + + +def pad_image_and_resize(image_path, target_size): + img = Image.open(image_path).convert('RGB') + max_side = max(img.size) + delta_w = max_side - img.size[0] + delta_h = max_side - img.size[1] + padding = (delta_w // 2, delta_h // 2, delta_w - delta_w // 2, delta_h - delta_h // 2) + img_padded = ImageOps.expand(img, padding, fill='black') + img_resized = img_padded.resize((target_size, target_size)) + return np.array(img_resized) + +def tile_and_stack(image, num_tiles_per_side): + 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.concatenate(tiles, axis=-1) + return stacked_image \ No newline at end of file diff --git a/code/main.py b/code/main.py new file mode 100644 index 0000000..bbe7c92 --- /dev/null +++ b/code/main.py @@ -0,0 +1,83 @@ +import os +import numpy as np +import tensorflow as tf +import data_adapter +import model + +from sklearn.model_selection import train_test_split + + +def load_dataset(image_paths, labels, target_size, num_tiles_per_side): + X, y = [], [] + for path, label in zip(image_paths, labels): + img = data_adapter.pad_image_and_resize(path, target_size) + img_tiled = data_adapter.tile_and_stack(img, num_tiles_per_side) + X.append(img_tiled) + y.append(label) + return np.array(X), np.array(y) + +# 5. Training and validation routines +def train_and_validate(model, X_train, y_train, X_val, y_val, epochs, batch_size): + history = model.fit( + X_train, y_train, + epochs=epochs, + batch_size=batch_size, + validation_data=(X_val, y_val) + ) + return history + +# 6. Parameter analysis and best model saving +def run_experiment(image_folder, target_image_size, num_tiles_per_side, ds_conv_filters, kernel_size, + hidden_units, dropout_rate, learning_rate, epochs, batch_size): + 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] + X, y = load_dataset(image_files, labels, target_image_size, num_tiles_per_side) + + X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, stratify=y) + + input_shape = X_train.shape[1:] + + clf_model = model.ForeignObjectClassificationModel(input_shape, ds_conv_filters, kernel_size=kernel_size, hidden_units, dropout_rate) + clf_model.compile(learning_rate) + + history = train_and_validate(clf_model.model, X_train, y_train, X_val, y_val, epochs, batch_size) + + val_acc = max(history.history['val_binary_accuracy']) + + model_save_path = f'model_acc_{val_acc:.2f}.h5' + clf_model.model.save(model_save_path) + + with open("training_log.txt", "a") as f: + f.write(f"params: tiles={num_tiles_per_side}, filters={ds_conv_filters}, hidden={hidden_units}, " + f"dropout={dropout_rate}, lr={learning_rate}, epochs={epochs}, batch_size={batch_size}, " + f"val_acc={val_acc:.4f}\n") + + print(f'Model saved as {model_save_path}') + +# 7. Testing function +def evaluate_best_model(model_path, test_image_folder, target_size, num_tiles_per_side): + model = tf.keras.models.load_model(model_path) + image_files = [os.path.join(test_image_folder, f) for f in os.listdir(test_image_folder)] + labels = [1 if 'fo_' in f else 0 for f in image_files] + + X_test, y_test = load_dataset(image_files, labels, target_size, num_tiles_per_side) + + loss, acc = model.evaluate(X_test, y_test) + print(f'Test accuracy: {acc:.4f}') + +# Example of usage +if __name__ == '__main__': + run_experiment( + image_folder='train_images', + target_image_size=256, + num_tiles_per_side=8, + ds_conv_filters=16, + kernel_size=3, + hidden_units=32, + dropout_rate=0.5, + learning_rate=0.001, + epochs=20, + batch_size=4 + ) + + evaluate_best_model('model_acc_0.90.h5', 'test_images', 256, 8) diff --git a/code/model.py b/code/model.py new file mode 100644 index 0000000..4ecc6e3 --- /dev/null +++ b/code/model.py @@ -0,0 +1,24 @@ +from tensorflow.keras.layers import DepthwiseConv2D, Conv2D, Dense, Dropout, Flatten, GlobalAveragePooling2D, Input +from tensorflow.keras.models import Model +from tensorflow.keras.optimizers import Adam +from tensorflow.keras.losses import BinaryCrossentropy +from tensorflow.keras.metrics import BinaryAccuracy + +class ForeignObjectClassificationModel: + def __init__(self, input_shape, ds_conv_filters, kernel_size, hidden_units, dropout_rate): + inputs = Input(shape=input_shape) + x = DepthwiseConv2D(kernel_size=kernel_size, padding='same', activation='relu')(inputs) + x = Conv2D(ds_conv_filters, kernel_size=1, activation='relu')(x) + x = GlobalAveragePooling2D()(x) + x = Dense(hidden_units, activation='relu')(x) + x = Dropout(dropout_rate)(x) + outputs = Dense(1, activation='sigmoid')(x) + + self.model = Model(inputs=inputs, outputs=outputs) + + def compile(self, learning_rate): + self.model.compile( + optimizer=Adam(learning_rate=learning_rate), + loss=BinaryCrossentropy(), + metrics=[BinaryAccuracy()] + ) \ No newline at end of file