{"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":8410120,"sourceType":"datasetVersion","datasetId":5005298}],"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-15T09:47:15.433601Z","iopub.execute_input":"2024-05-15T09:47:15.434036Z","iopub.status.idle":"2024-05-15T09:47:28.520005Z","shell.execute_reply.started":"2024-05-15T09:47:15.434000Z","shell.execute_reply":"2024-05-15T09:47:28.518579Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport skimage.io\nimport seaborn as sns\nfrom skimage.transform import resize\nfrom imgaug import augmenters as iaa\nfrom tqdm import tqdm\nimport PIL\nfrom PIL import Image, ImageOps\nimport cv2\n\nWORKERS = 2\nCHANNEL = 3\n%matplotlib inline\nsns.set(style=\"whitegrid\")\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nIMG_SIZE = 512\nNUM_CLASSES = 5\nSEED = 77\nTRAIN_NUM = 1000 # use 1000 when you just want to explore new idea, use -1 for full train","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:47:28.522504Z","iopub.execute_input":"2024-05-15T09:47:28.523472Z","iopub.status.idle":"2024-05-15T09:47:30.649331Z","shell.execute_reply.started":"2024-05-15T09:47:28.523424Z","shell.execute_reply":"2024-05-15T09:47:30.647302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications import MobileNet\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout\nfrom keras.models import Model\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, BatchNormalization\\\n\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import AveragePooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nprint('Model Loaded ')","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:47:30.651060Z","iopub.execute_input":"2024-05-15T09:47:30.651685Z","iopub.status.idle":"2024-05-15T09:47:48.243861Z","shell.execute_reply.started":"2024-05-15T09:47:30.651646Z","shell.execute_reply":"2024-05-15T09:47:48.242489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df=pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\nprint('Number of train samples: ', train_df.shape[0])\nf, ax = plt.subplots(figsize=(10,6))\nax = sns.countplot(x=\"diagnosis\", data=train_df, palette=\"GnBu_d\")\nsns.despine()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:51:03.354282Z","iopub.execute_input":"2024-05-15T09:51:03.354696Z","iopub.status.idle":"2024-05-15T09:51:03.665536Z","shell.execute_reply.started":"2024-05-15T09:51:03.354657Z","shell.execute_reply":"2024-05-15T09:51:03.664360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfig = plt.figure(figsize=(25, 16))\n#display 10 images from each class\nfor class_id in sorted(train_df['diagnosis'].unique()):\n    for i, (idx, row) in enumerate(train_df.loc[train_df['diagnosis'] == class_id].sample(5, random_state=SEED).iterrows()):\n        ax = fig.add_subplot(5, 5, class_id * 5 + i + 1, xticks=[], yticks=[])\n        path=f\"/kaggle/input/processed-train-images/train_images/{row['id_code']}.png\"\n        image = cv2.imread(path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n\n        plt.imshow(image)\n        ax.set_title('Label: %d-%d-%s' % (class_id, idx, row['id_code']) )","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:52:36.539946Z","iopub.execute_input":"2024-05-15T09:52:36.540353Z","iopub.status.idle":"2024-05-15T09:52:43.435671Z","shell.execute_reply.started":"2024-05-15T09:52:36.540322Z","shell.execute_reply":"2024-05-15T09:52:43.434413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from imblearn.over_sampling import RandomOverSampler","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:54:56.206092Z","iopub.execute_input":"2024-05-15T09:54:56.206551Z","iopub.status.idle":"2024-05-15T09:54:56.211951Z","shell.execute_reply.started":"2024-05-15T09:54:56.206518Z","shell.execute_reply":"2024-05-15T09:54:56.210448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Assuming your CSV has columns 'filename' and 'label' representing image filenames and their labels\nimage_dir = '/kaggle/input/processed-train-images/train_images'  # Directory containing your image files\n\n#Create a list of file paths and corresponding labels\nfile_paths = [os.path.join(image_dir, id_code) for id_code in train_df['id_code']]\ndiagnosis = train_df['diagnosis'].values\n\n#Convert file paths and labels to arrays\nX_train = np.array(file_paths)\ny_train = np.array(diagnosis)\n\n#Convert arrays to DataFrame for oversampling\notrain_df = pd.DataFrame({'id_code': X_train, 'diagnosis': y_train})","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:54:59.611883Z","iopub.execute_input":"2024-05-15T09:54:59.612316Z","iopub.status.idle":"2024-05-15T09:54:59.632628Z","shell.execute_reply.started":"2024-05-15T09:54:59.612282Z","shell.execute_reply":"2024-05-15T09:54:59.631450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Visualize class distribution before oversampling\nclass_counts_before = otrain_df['diagnosis'].value_counts()\nprint(\"Class Distribution Before Oversampling:\")\nprint(class_counts_before)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:55:13.195859Z","iopub.execute_input":"2024-05-15T09:55:13.196285Z","iopub.status.idle":"2024-05-15T09:55:13.208373Z","shell.execute_reply.started":"2024-05-15T09:55:13.196254Z","shell.execute_reply":"2024-05-15T09:55:13.207018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Apply random oversampling\nros = RandomOverSampler(random_state=42)\nX_train_ros, y_train_ros = ros.fit_resample(otrain_df[['id_code']], otrain_df['diagnosis'])\n\n#Optional: Check the shape of X_train_ros\n#print(X_train_ros.shape)  # Check if squeezing is necessary\n#Convert oversampled arrays back to DataFrame (squeezing might be needed)\noversampled_df = pd.DataFrame({'id_code': X_train_ros.squeeze() if len(X_train_ros.shape) > 1 else X_train_ros, 'diagnosis': y_train_ros})","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:56:21.844233Z","iopub.execute_input":"2024-05-15T09:56:21.844623Z","iopub.status.idle":"2024-05-15T09:56:21.863402Z","shell.execute_reply.started":"2024-05-15T09:56:21.844596Z","shell.execute_reply":"2024-05-15T09:56:21.862001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Visualize class distribution after oversampling\nclass_counts_after = oversampled_df['diagnosis'].value_counts()\nprint(\"\\nClass Distribution After Random Oversampling:\")\nprint(class_counts_after)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:56:35.250435Z","iopub.execute_input":"2024-05-15T09:56:35.250830Z","iopub.status.idle":"2024-05-15T09:56:35.260465Z","shell.execute_reply.started":"2024-05-15T09:56:35.250802Z","shell.execute_reply":"2024-05-15T09:56:35.259552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ndef load_image(filepath):\n  \"\"\"\n  Loads an image from the specified filepath using OpenCV (cv2).\n\n  Args:\n      filepath (str): The path to the image file.\n\n  Returns:\n      numpy.ndarray: The loaded image as a NumPy array, or None if loading fails.\n  \"\"\"\n  try:\n    return cv2.imread(filepath)\n  except (cv2.error, FileNotFoundError):\n    print(f\"Error loading image: {filepath}\")\n    return None  # Handle loading errors gracefully (e.g., logging or skipping)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:56:46.048293Z","iopub.execute_input":"2024-05-15T09:56:46.048756Z","iopub.status.idle":"2024-05-15T09:56:46.055897Z","shell.execute_reply.started":"2024-05-15T09:56:46.048725Z","shell.execute_reply":"2024-05-15T09:56:46.054453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Split data into training, validation, and testing sets\nX_train, X_test, y_train, y_test = train_test_split(X_train_ros, y_train_ros, test_size=0.2, random_state=SEED)\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=SEED)\n#Now you have your training, validation, and testing sets ready for model training!\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T09:57:19.331498Z","iopub.execute_input":"2024-05-15T09:57:19.332134Z","iopub.status.idle":"2024-05-15T09:57:19.344942Z","shell.execute_reply.started":"2024-05-15T09:57:19.332088Z","shell.execute_reply":"2024-05-15T09:57:19.343343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def visualize_data_split(X_train, X_val, X_test, y_train, y_val, y_test, labels):\n  \"\"\"\n  Visualizes the data splitting process using bar charts.\n\n  Args:\n      X_train, X_val, X_test (list): Lists containing training, validation, and testing data.\n      y_train, y_val, y_test (list): Lists containing training, validation, and testing labels.\n      labels (list): List of class labels (optional).\n  \"\"\"\n\n  # Calculate data point counts\n  train_count = len(X_train)\n  val_count = len(X_val)\n  test_count = len(X_test)\n\n  # Create bar chart\n  fig, ax = plt.subplots()\n  ax.bar([0, 1, 2], [train_count, val_count, test_count], color=['royalblue', 'gold', 'lightcoral'])\n  ax.set_xlabel('Data Split')\n  ax.set_ylabel('Number of Data Points')\n  ax.set_title('Data Split Visualization')\n\n  # Check if labels is not empty (has elements)\n  if labels.any() and len(labels) > 0:\n    ax.set_xticks([0, 1, 2])\n    ax.set_xticklabels(['Training', 'Validation', 'Testing'])\n  ax.grid(axis='y')\n  plt.show()\n\n#Assuming you have split your data into X_train, X_val, X_test, y_train, y_val, y_test\nvisualize_data_split(X_train, X_val, X_test, y_train, y_val, y_test, labels=train_df['diagnosis'].unique())  # If you have class labels","metadata":{"execution":{"iopub.status.busy":"2024-05-15T11:04:04.000363Z","iopub.execute_input":"2024-05-15T11:04:04.000765Z","iopub.status.idle":"2024-05-15T11:04:04.629354Z","shell.execute_reply.started":"2024-05-15T11:04:04.000728Z","shell.execute_reply":"2024-05-15T11:04:04.628200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_size = (224,224,3)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T11:04:51.634362Z","iopub.execute_input":"2024-05-15T11:04:51.634782Z","iopub.status.idle":"2024-05-15T11:04:51.640747Z","shell.execute_reply.started":"2024-05-15T11:04:51.634740Z","shell.execute_reply":"2024-05-15T11:04:51.639211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = MobileNet(input_shape=image_size, weights='imagenet', include_top=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T11:05:04.182574Z","iopub.execute_input":"2024-05-15T11:05:04.182940Z","iopub.status.idle":"2024-05-15T11:05:05.413418Z","shell.execute_reply.started":"2024-05-15T11:05:04.182914Z","shell.execute_reply":"2024-05-15T11:05:05.412060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}