# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python [conda env:PythonAdv]
#     language: python
#     name: conda-env-PythonAdv-py
# ---

# +
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import os

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout, BatchNormalization, Activation
from tensorflow.keras.optimizers import Adam

# +
# Bring in train and test data 
X_train = np.load('./Data/X_train.npy')
X_test = np.load('./Data/X_test.npy')

y_train = np.load('./Data/y_train.npy')
y_test = np.load('./Data/y_test.npy')

# +
# Set dimensions of images, 1 for one layer
im_shape = (360, 480, 1)

X_train = X_train.reshape(X_train.shape[0], *im_shape)
X_test = X_test.reshape(X_test.shape[0], *im_shape)
# -

# ### Build CNN model using AlexNet architecture

cnn_model = Sequential([
    Conv2D(filters=96, kernel_size=(13, 13), strides=4,  input_shape=im_shape),
    BatchNormalization(axis=3),
    Activation('relu'),
    MaxPooling2D(pool_size=(3, 3), strides=2),
    Dropout(0.2),
    Conv2D(filters=256, kernel_size=(7, 7), padding='same'),
    BatchNormalization(axis=3),
    Activation('relu'),
    MaxPooling2D(pool_size=(3, 3), strides=2),
    Dropout(0.2),
    Conv2D(filters=384, kernel_size=(3, 3), padding='same'),
    BatchNormalization(axis=3),
    Activation('relu'),
    Dropout(0.2),
    Conv2D(filters=384, kernel_size=(3, 3), padding='same'),
    BatchNormalization(axis=3),
    Activation('relu'),
    Dropout(0.2),
    Conv2D(filters=256, kernel_size=(3, 3), padding='same'),
    BatchNormalization(axis=3),
    Activation('relu'),
    Dropout(0.2),
    MaxPooling2D(pool_size=(3, 3), strides=2),
    Flatten(),
    Dense(4096, activation='relu'),
    Dense(4096, activation='relu'),
    Dense(2, activation='softmax')
])

cnn_model.compile(
    loss='sparse_categorical_crossentropy',
    optimizer=Adam(lr=0.001),
    metrics=['accuracy']
)

cnn_model.fit(
    X_train, y_train, batch_size=100,
    epochs=46, verbose=1,
    validation_data=(X_test, y_test)
)

score = cnn_model.evaluate(X_test, y_test, verbose=2)
print(f"Loss: {score[0]}, Accuracy: {score[1]}")

cnn_model.save('cnn_model.h5')

StarcoderdataJupyterScriptsDedupFiltered