{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"},{"sourceId":177989207,"sourceType":"kernelVersion"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-16T18:21:25.366836Z","iopub.execute_input":"2024-05-16T18:21:25.367311Z","iopub.status.idle":"2024-05-16T18:21:31.698059Z","shell.execute_reply.started":"2024-05-16T18:21:25.367275Z","shell.execute_reply":"2024-05-16T18:21:31.696350Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport shutil\nimport random\nimport numpy as np\nimport pandas as pd\nimport cv2\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom imblearn.over_sampling import RandomOverSampler\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization, Dropout\nfrom tensorflow.keras.optimizers import Adam\nimport pandas as pd\nimport numpy as np\nimport os\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport math\nimport tensorflow as tf\nimport keras\nfrom keras import models\nfrom keras import layers\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D , SeparableConv2D, MaxPooling2D , Flatten , Dropout , BatchNormalization, Activation\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nfrom tensorflow.keras.utils import img_to_array,array_to_img\nfrom keras.callbacks import ReduceLROnPlateau \nfrom keras import backend as K\nfrom keras import optimizers\nfrom sklearn.metrics import classification_report, recall_score, precision_score, confusion_matrix, f1_score, accuracy_score\nfrom tensorflow.keras.utils import plot_model\nfrom IPython.display import Image\nimport pandas as pd\nimport numpy as np\nimport os\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport math\nimport tensorflow as tf\nimport keras\nfrom tensorflow.keras.models import Sequential\nfrom keras import models\nfrom keras import layers\nfrom keras import optimizers\n\nfrom tensorflow.keras.applications import ResNet152V2\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom tensorflow.keras import backend as K\n\n\nfrom keras.layers import Dense, Conv2D , SeparableConv2D, MaxPooling2D , Flatten , Dropout , BatchNormalization, Activation\n\nfrom tensorflow.keras.utils import img_to_array,array_to_img\nfrom keras.callbacks import ReduceLROnPlateau \n\nfrom keras import optimizers\nfrom sklearn.metrics import classification_report, recall_score, precision_score, confusion_matrix, f1_score, accuracy_score\nfrom tensorflow.keras.utils import plot_model\nfrom IPython.display import Image\n\n\n\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.optimizers import Adam, Adamax\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.metrics import categorical_crossentropy\nfrom tensorflow.keras.models import Model, load_model, Sequential\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Activation, Dropout, BatchNormalization\nprint ('modules loaded')","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:21:43.651485Z","iopub.execute_input":"2024-05-16T18:21:43.652045Z","iopub.status.idle":"2024-05-16T18:21:53.385847Z","shell.execute_reply.started":"2024-05-16T18:21:43.652001Z","shell.execute_reply":"2024-05-16T18:21:53.384258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Constants\nSEED = 42\nIMG_SIZE = (224, 224)\nBATCH_SIZE = 32\nNUM_CLASSES = 5\n","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:22:04.661946Z","iopub.execute_input":"2024-05-16T18:22:04.662933Z","iopub.status.idle":"2024-05-16T18:22:04.669698Z","shell.execute_reply.started":"2024-05-16T18:22:04.662882Z","shell.execute_reply":"2024-05-16T18:22:04.668448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load train data\ntrain_df = pd.read_csv('../input/aptos2019-blindness-detection/train.csv')","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:22:14.286620Z","iopub.execute_input":"2024-05-16T18:22:14.287911Z","iopub.status.idle":"2024-05-16T18:22:14.313071Z","shell.execute_reply.started":"2024-05-16T18:22:14.287868Z","shell.execute_reply":"2024-05-16T18:22:14.311616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to load image\ndef load_image(filepath):\n    try:\n        return cv2.imread(filepath)\n    except (cv2.error, FileNotFoundError):\n        print(f\"Error loading image: {filepath}\")\n        return None\n","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:22:24.547551Z","iopub.execute_input":"2024-05-16T18:22:24.548050Z","iopub.status.idle":"2024-05-16T18:22:24.555793Z","shell.execute_reply.started":"2024-05-16T18:22:24.548015Z","shell.execute_reply":"2024-05-16T18:22:24.554292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Directory containing image files\nimage_dir = '/kaggle/input/dr-ai-preprocessing/train_images'\nfile_paths = [os.path.join(image_dir, id_code+'.png') for id_code in train_df['id_code']]\ndiagnosis = train_df['diagnosis'].values","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:22:49.635578Z","iopub.execute_input":"2024-05-16T18:22:49.636151Z","iopub.status.idle":"2024-05-16T18:22:49.661767Z","shell.execute_reply.started":"2024-05-16T18:22:49.636099Z","shell.execute_reply":"2024-05-16T18:22:49.659958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Apply random oversampling with balanced sampling strategy\nros = RandomOverSampler(random_state=SEED, sampling_strategy='auto')\nfile_paths_resampled, diagnosis_resampled = ros.fit_resample(np.array(file_paths).reshape(-1, 1), diagnosis)\n\n# Convert oversampled arrays back to lists\nfile_paths_resampled = file_paths_resampled.flatten().tolist()\n\n# Shuffle the oversampled data\nfile_paths_resampled, diagnosis_resampled = shuffle(file_paths_resampled, diagnosis_resampled, random_state=SEED)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:23:01.133648Z","iopub.execute_input":"2024-05-16T18:23:01.134160Z","iopub.status.idle":"2024-05-16T18:23:01.162341Z","shell.execute_reply.started":"2024-05-16T18:23:01.134125Z","shell.execute_reply":"2024-05-16T18:23:01.161062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split data into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(file_paths_resampled, diagnosis_resampled, test_size=0.25, random_state=SEED)\n\n# Directories for train and validation data\nbase_dir = '/kaggle/working'\ntrain_dir = os.path.join(base_dir, 'train')\nval_dir = os.path.join(base_dir, 'validation')\n\n# Function to organize data into directories\ndef organize_data_into_directories(file_paths, labels, directory):\n    for file_path, label in zip(file_paths, labels):\n        label_dir = os.path.join(directory, str(label))\n        os.makedirs(label_dir, exist_ok=True)\n        shutil.copy(file_path, label_dir)\n\n# Organize data into directories\norganize_data_into_directories(X_train, y_train, train_dir)\norganize_data_into_directories(X_val, y_val, val_dir)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:23:19.742067Z","iopub.execute_input":"2024-05-16T18:23:19.742541Z","iopub.status.idle":"2024-05-16T18:27:05.977898Z","shell.execute_reply.started":"2024-05-16T18:23:19.742506Z","shell.execute_reply":"2024-05-16T18:27:05.973433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define data generators with data augmentation\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True\n)\nval_datagen = ImageDataGenerator(rescale=1./255)\n\n# Data generators\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=IMG_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode='categorical'\n)\n\nval_generator = val_datagen.flow_from_directory(\n    val_dir,\n    target_size=IMG_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode='categorical'\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:27:18.943992Z","iopub.execute_input":"2024-05-16T18:27:18.945742Z","iopub.status.idle":"2024-05-16T18:27:19.137834Z","shell.execute_reply.started":"2024-05-16T18:27:18.945665Z","shell.execute_reply":"2024-05-16T18:27:19.136517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_size = (224,224,3)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:28:44.633870Z","iopub.execute_input":"2024-05-16T18:28:44.634452Z","iopub.status.idle":"2024-05-16T18:28:44.642054Z","shell.execute_reply.started":"2024-05-16T18:28:44.634416Z","shell.execute_reply":"2024-05-16T18:28:44.640924Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the base model\nbase_model = ResNet152V2(input_shape=image_size, include_top=False, weights=\"imagenet\")","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:28:48.887711Z","iopub.execute_input":"2024-05-16T18:28:48.888565Z","iopub.status.idle":"2024-05-16T18:28:56.859093Z","shell.execute_reply.started":"2024-05-16T18:28:48.888511Z","shell.execute_reply":"2024-05-16T18:28:56.857356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Freeze the layers in the base model, except for the last 10 layers\nfor layer in base_model.layers[:-10]:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:29:09.113150Z","iopub.execute_input":"2024-05-16T18:29:09.113679Z","iopub.status.idle":"2024-05-16T18:29:09.139510Z","shell.execute_reply.started":"2024-05-16T18:29:09.113638Z","shell.execute_reply":"2024-05-16T18:29:09.137430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create the Sequential model\nmodel = Sequential()\nmodel.add(base_model)\nmodel.add(Dropout(0.5))\nmodel.add(Flatten())\nmodel.add(BatchNormalization())\nmodel.add(Dense(256, kernel_initializer='he_uniform'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(128, kernel_initializer='he_uniform'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(32, kernel_initializer='he_uniform'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dense(5, activation='softmax'))","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:29:20.013914Z","iopub.execute_input":"2024-05-16T18:29:20.014444Z","iopub.status.idle":"2024-05-16T18:29:20.061289Z","shell.execute_reply.started":"2024-05-16T18:29:20.014412Z","shell.execute_reply":"2024-05-16T18:29:20.059678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the custom F1 score function\ndef f1_score(y_true, y_pred):\n    true_positives = tf.math.reduce_sum(tf.round(tf.clip_by_value(y_true * y_pred, 0, 1)))\n    possible_positives = tf.math.reduce_sum(tf.round(tf.clip_by_value(y_true, 0, 1)))\n    predicted_positives = tf.math.reduce_sum(tf.round(tf.clip_by_value(y_pred, 0, 1)))\n    precision = true_positives / (predicted_positives + K.epsilon())\n    recall = true_positives / (possible_positives + K.epsilon())\n    f1_val = 2 * (precision * recall) / (precision + recall + K.epsilon())\n    return f1_val","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:29:30.469689Z","iopub.execute_input":"2024-05-16T18:29:30.471439Z","iopub.status.idle":"2024-05-16T18:29:30.488086Z","shell.execute_reply.started":"2024-05-16T18:29:30.471373Z","shell.execute_reply":"2024-05-16T18:29:30.485794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the metrics for the model\nMETRICS = [\n    tf.keras.metrics.CategoricalAccuracy(name='accuracy'),\n    tf.keras.metrics.Precision(name='precision'),\n    tf.keras.metrics.Recall(name='recall'),\n    tf.keras.metrics.AUC(name='auc'),\n    f1_score,\n]","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:29:40.039781Z","iopub.execute_input":"2024-05-16T18:29:40.040287Z","iopub.status.idle":"2024-05-16T18:29:40.076821Z","shell.execute_reply.started":"2024-05-16T18:29:40.040252Z","shell.execute_reply":"2024-05-16T18:29:40.074918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=METRICS)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:29:47.729231Z","iopub.execute_input":"2024-05-16T18:29:47.730233Z","iopub.status.idle":"2024-05-16T18:29:47.753075Z","shell.execute_reply.started":"2024-05-16T18:29:47.730177Z","shell.execute_reply":"2024-05-16T18:29:47.751931Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the base directory and model path\nbase_dir = '/kaggle/working/Models'\nmodel_path = os.path.join(base_dir, 'ResNet52.keras')\n\n# Check if the model file already exists, and remove it if it does\nif os.path.isfile(model_path):\n    os.remove(model_path)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:30:09.818374Z","iopub.execute_input":"2024-05-16T18:30:09.818936Z","iopub.status.idle":"2024-05-16T18:30:09.826306Z","shell.execute_reply.started":"2024-05-16T18:30:09.818897Z","shell.execute_reply":"2024-05-16T18:30:09.824845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the number of epochs and callbacks for training\nEPOCHS = 30\nearlystop = EarlyStopping(verbose=1, patience=5)\nlearning_rate_reduction = ReduceLROnPlateau(\n    monitor='val_loss',\n    patience=2,\n    verbose=1,\n    factor=0.8,\n    min_lr=1e-6\n)\n\n# Define the model checkpoint callback\ncheckpoint = ModelCheckpoint(\n    model_path,\n    monitor='val_loss',\n    verbose=1,\n    save_best_only=True,\n    mode='min',\n    save_weights_only=False\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:30:38.484675Z","iopub.execute_input":"2024-05-16T18:30:38.486485Z","iopub.status.idle":"2024-05-16T18:30:38.496210Z","shell.execute_reply.started":"2024-05-16T18:30:38.486429Z","shell.execute_reply":"2024-05-16T18:30:38.494310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Combine the callbacks\nmycallbacks = [earlystop, learning_rate_reduction, checkpoint]","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:30:48.255667Z","iopub.execute_input":"2024-05-16T18:30:48.256184Z","iopub.status.idle":"2024-05-16T18:30:48.263172Z","shell.execute_reply.started":"2024-05-16T18:30:48.256151Z","shell.execute_reply":"2024-05-16T18:30:48.261511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\nhistory = model.fit(\n    train_generator,\n    validation_data=val_generator,\n    epochs=EPOCHS,\n    callbacks=mycallbacks\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T18:32:12.759119Z","iopub.execute_input":"2024-05-16T18:32:12.759672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"complete_datagen = ImageDataGenerator(\n        rescale=1./255,\n        horizontal_flip = True,\n        )\n\ncomplete_generator = complete_datagen.flow_from_directory(\n        directory = train_dir,\n        target_size=(224, 224),\n        batch_size=1,\n        class_mode=None,\n        )","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"STEP_SIZE_COMPLETE = complete_generator.n//complete_generator.batch_size\ntrain_preds = model.predict(complete_generator, steps=STEP_SIZE_COMPLETE)\ntrain_preds = [np.argmax(pred) for pred in train_preds]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(set(train_preds))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.unique(complete_generator.classes, return_counts=True)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(5):\n    value = train_preds.count(i)\n    print(f'Class {i} -> {value}')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = '/kaggle/working/Models/ResNet52.keras'\nmodel.save(model_path)","metadata":{},"execution_count":null,"outputs":[]}]}