{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.6"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"},{"sourceId":187731,"sourceType":"datasetVersion","datasetId":80814},{"sourceId":418031,"sourceType":"datasetVersion","datasetId":131128},{"sourceId":9900,"sourceType":"datasetVersion","datasetId":6209}],"dockerImageVersionId":28450,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# DenseNet Trained with Old and New Data\n\n---\n\nDue to the size of previous competition's data, I faced few memory-related problems while training my model. In this kernel I would like to show the approach I used.\n\nI basically splitted the training set in buckets and trained the model for each bucket.\n\nI'd truly interested to further discuss how it could has been solved. So, if you faced the same issues, please comment with your ideas :)\n\n#### Here you can find the [Inference Kernel](https://www.kaggle.com/raimonds1993/aptos19-densenet-inference-old-new-data/data?scriptVersionId=17252732)!\n\n---","metadata":{}},{"cell_type":"markdown","source":"### Credits\nI started this kernel by forking [APTOS 2019: DenseNet Keras Starter](https://www.kaggle.com/xhlulu/aptos-2019-densenet-keras-starter), by [Xhlulu](https://www.kaggle.com/xhlulu).\n\nI also used [previous competition's data](https://www.kaggle.com/tanlikesmath/diabetic-retinopathy-resized) uploaded by [ilovescience](https://www.kaggle.com/tanlikesmath).\n\nThank you both guys!","metadata":{}},{"cell_type":"markdown","source":"### Changes\n\n*Version 3:*\n- This is the first completed version to consider. (Still without seed)\n- Inference -> LB: 0.719\n\n*Version 4:*\n- Updated image size (320). In order to process the whole dataset, I load just one bucket at a time and trained the model on that.\n- Added seed to better evaluate the results.\n\n*Version 5:*\n- Changed train - val split: Now let's take previous comp data as train and the new comp data as validation\n\n*Version 9:*\n- Changed preprosessing filter in old (train) data\n- Changed Imagegenerator , more augmentation\n\n*Version 10:*\n- No Cropping in old comp data","metadata":{}},{"cell_type":"code","source":"# To have reproducible results and compare them\nnr_seed = 2019\nimport numpy as np \nnp.random.seed(nr_seed)\nimport tensorflow as tf\ntf.set_random_seed(nr_seed)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T18:45:33.86002Z","iopub.execute_input":"2025-04-07T18:45:33.860308Z","iopub.status.idle":"2025-04-07T18:45:33.864516Z","shell.execute_reply.started":"2025-04-07T18:45:33.860268Z","shell.execute_reply":"2025-04-07T18:45:33.863691Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import libraries\nimport json\nimport math\nfrom tqdm import tqdm, tqdm_notebook\nimport gc\nimport warnings\nimport os\n\nimport cv2\nfrom PIL import Image\n\nimport pandas as pd\nimport scipy\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras import layers\nfrom tensorflow.keras.applications import ResNet50\nfrom keras.callbacks import Callback, ModelCheckpoint\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import cohen_kappa_score, accuracy_score\n\nwarnings.filterwarnings(\"ignore\")\n\n%matplotlib inline","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2025-04-07T18:48:18.288333Z","iopub.execute_input":"2025-04-07T18:48:18.288596Z","iopub.status.idle":"2025-04-07T18:48:18.912119Z","shell.execute_reply.started":"2025-04-07T18:48:18.288558Z","shell.execute_reply":"2025-04-07T18:48:18.911166Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Image size\nim_size = 320\n# Batch size\nBATCH_SIZE = 32","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T18:48:28.237632Z","iopub.execute_input":"2025-04-07T18:48:28.237927Z","iopub.status.idle":"2025-04-07T18:48:28.241479Z","shell.execute_reply.started":"2025-04-07T18:48:28.237868Z","shell.execute_reply":"2025-04-07T18:48:28.240711Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Loading & Merging","metadata":{}},{"cell_type":"code","source":"new_train = pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\nold_train = pd.read_csv('../input/diabetic-retinopathy-resized/trainLabels.csv')\nprint(new_train.shape)\nprint(old_train.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T18:48:31.191278Z","iopub.execute_input":"2025-04-07T18:48:31.191597Z","iopub.status.idle":"2025-04-07T18:48:31.247926Z","shell.execute_reply.started":"2025-04-07T18:48:31.191533Z","shell.execute_reply":"2025-04-07T18:48:31.247158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"old_train = old_train[['image','level']]\nold_train.columns = new_train.columns\nold_train.diagnosis.value_counts()\n\n# path columns\nnew_train['id_code'] = '../input/aptos2019-blindness-detection/train_images/' + new_train['id_code'].astype(str) + '.png'\nold_train['id_code'] = '../input/diabetic-retinopathy-resized/resized_train/resized_train/' + old_train['id_code'].astype(str) + '.jpeg'\n\ntrain_df = old_train.copy()\nval_df = new_train.copy()\ntrain_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T18:48:33.723156Z","iopub.execute_input":"2025-04-07T18:48:33.723434Z","iopub.status.idle":"2025-04-07T18:48:33.863771Z","shell.execute_reply.started":"2025-04-07T18:48:33.723394Z","shell.execute_reply":"2025-04-07T18:48:33.862803Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Train - Valid split","metadata":{}},{"cell_type":"code","source":"# Not used in version 5\n#train_df, val_df = train_test_split(train_df, shuffle=True, stratify=train_df.diagnosis, test_size=0.1, random_state=2019)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Let's shuffle the datasets\ntrain_df = train_df.sample(frac=1).reset_index(drop=True)\nval_df = val_df.sample(frac=1).reset_index(drop=True)\nprint(train_df.shape)\nprint(val_df.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T18:48:38.474619Z","iopub.execute_input":"2025-04-07T18:48:38.474939Z","iopub.status.idle":"2025-04-07T18:48:38.487796Z","shell.execute_reply.started":"2025-04-07T18:48:38.474871Z","shell.execute_reply":"2025-04-07T18:48:38.487177Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Process Images","metadata":{}},{"cell_type":"markdown","source":"Crop function: https://www.kaggle.com/ratthachat/aptos-updated-preprocessing-ben-s-cropping ","metadata":{}},{"cell_type":"code","source":"def crop_image1(img,tol=7):\n    # img is image data\n    # tol  is tolerance\n        \n    mask = img>tol\n    return img[np.ix_(mask.any(1),mask.any(0))]\n\ndef crop_image_from_gray(img,tol=7):\n    if img.ndim ==2:\n        mask = img>tol\n        return img[np.ix_(mask.any(1),mask.any(0))]\n    elif img.ndim==3:\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n        mask = gray_img>tol\n        \n        check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n        if (check_shape == 0): # image is too dark so that we crop out everything,\n            return img # return original image\n        else:\n            img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n            img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n            img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n            img = np.stack([img1,img2,img3],axis=-1)\n        return img\n\ndef preprocess_image(image_path, desired_size=224):\n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = crop_image_from_gray(img)\n    img = cv2.resize(img, (desired_size,desired_size))\n    img = cv2.addWeighted(img,4,cv2.GaussianBlur(img, (0,0), desired_size/30) ,-4 ,128)\n    \n    return img\n\ndef preprocess_image_old(image_path, desired_size=224):\n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    #img = crop_image_from_gray(img)\n    img = cv2.resize(img, (desired_size,desired_size))\n    img = cv2.addWeighted(img,4,cv2.GaussianBlur(img, (0,0), desired_size/40) ,-4 ,128)\n    \n    return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T18:48:41.123672Z","iopub.execute_input":"2025-04-07T18:48:41.124006Z","iopub.status.idle":"2025-04-07T18:48:41.136304Z","shell.execute_reply.started":"2025-04-07T18:48:41.123947Z","shell.execute_reply":"2025-04-07T18:48:41.135479Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def display_samples(df, columns=4, rows=3):\n    fig=plt.figure(figsize=(5*columns, 4*rows))\n\n    for i in range(columns*rows):\n        image_path = df.loc[i,'id_code']\n        image_id = df.loc[i,'diagnosis']\n        img = cv2.imread(f'{image_path}')\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        #img = crop_image_from_gray(img)\n        img = cv2.resize(img, (im_size,im_size))\n        img = cv2.addWeighted(img,4,cv2.GaussianBlur(img, (0,0), im_size/40) ,-4 ,128)\n        \n        fig.add_subplot(rows, columns, i+1)\n        plt.title(image_id)\n        plt.imshow(img)\n    \n    plt.tight_layout()\n\ndisplay_samples(train_df)","metadata":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T18:48:48.774033Z","iopub.execute_input":"2025-04-07T18:48:48.774313Z","iopub.status.idle":"2025-04-07T18:48:52.618804Z","shell.execute_reply.started":"2025-04-07T18:48:48.774273Z","shell.execute_reply":"2025-04-07T18:48:52.617821Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Processing Images","metadata":{}},{"cell_type":"markdown","source":"__UPDATE:__ Here we are reading just the validation set. In order to use 320x320 images, we are going to load one bucket at a time only when needed. This will let our code run without memory-related errors.","metadata":{}},{"cell_type":"code","source":"pip install -U ipywidgets\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T18:50:41.858573Z","iopub.execute_input":"2025-04-07T18:50:41.85884Z","iopub.status.idle":"2025-04-07T18:50:57.64397Z","shell.execute_reply.started":"2025-04-07T18:50:41.858799Z","shell.execute_reply":"2025-04-07T18:50:57.642879Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pip install jupyterlab_widgets\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:00:58.704106Z","iopub.execute_input":"2025-04-07T19:00:58.704381Z","iopub.status.idle":"2025-04-07T19:01:04.021831Z","shell.execute_reply.started":"2025-04-07T19:00:58.704342Z","shell.execute_reply":"2025-04-07T19:01:04.02084Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nimport os\n\n# Image size\nim_size = 224  # or whatever size you're using\n\n# Load validation dataframe (adjust the path if needed)\nval_df = pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\n\n# If you've split the dataset earlier into train and val, filter it again here\n# For demo, we'll just reuse the full data as validation (replace with your own val_df if available)\n# val_df = val_df.sample(frac=0.2, random_state=42)  # Example: take 20% for validation\n\n# Path to image folder\nimage_dir = '../input/aptos2019-blindness-detection/train_images/'\n\n# Preallocate validation image array\nN = val_df.shape[0]\nx_val = np.empty((N, im_size, im_size, 3), dtype=np.uint8)\n\n# Preprocess images\nfor i, image_id in enumerate(tqdm(val_df['id_code'], desc=\"Processing validation images\")):\n    image_path = os.path.join(image_dir, image_id + '.png')\n    x_val[i] = preprocess_image(image_path, desired_size=im_size)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:10:55.165649Z","iopub.execute_input":"2025-04-07T19:10:55.165975Z","iopub.status.idle":"2025-04-07T19:19:48.857973Z","shell.execute_reply.started":"2025-04-07T19:10:55.165928Z","shell.execute_reply":"2025-04-07T19:19:48.857123Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_train = pd.get_dummies(train_df['diagnosis']).values\ny_val = pd.get_dummies(val_df['diagnosis']).values\n\nprint(y_train.shape)\nprint(x_val.shape)\nprint(y_val.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:29:47.316552Z","iopub.execute_input":"2025-04-07T19:29:47.316806Z","iopub.status.idle":"2025-04-07T19:29:47.324573Z","shell.execute_reply.started":"2025-04-07T19:29:47.316766Z","shell.execute_reply":"2025-04-07T19:29:47.323898Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Creating multilabels\n\nInstead of predicting a single label, we will change our target to be a multilabel problem; i.e., if the target is a certain class, then it encompasses all the classes before it. E.g. encoding a class 4 retinopathy would usually be `[0, 0, 0, 1]`, but in our case we will predict `[1, 1, 1, 1]`. For more details, please check out [Lex's kernel](https://www.kaggle.com/lextoumbourou/blindness-detection-resnet34-ordinal-targets).","metadata":{}},{"cell_type":"code","source":"y_train_multi = np.empty(y_train.shape, dtype=y_train.dtype)\ny_train_multi[:, 4] = y_train[:, 4]\n\nfor i in range(3, -1, -1):\n    y_train_multi[:, i] = np.logical_or(y_train[:, i], y_train_multi[:, i+1])\n\ny_val_multi = np.empty(y_val.shape, dtype=y_val.dtype)\ny_val_multi[:, 4] = y_val[:, 4]\n\nfor i in range(3, -1, -1):\n    y_val_multi[:, i] = np.logical_or(y_val[:, i], y_val_multi[:, i+1])\n\nprint(\"Y_train multi: {}\".format(y_train_multi.shape))\nprint(\"Y_val multi: {}\".format(y_val_multi.shape))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:29:49.267467Z","iopub.execute_input":"2025-04-07T19:29:49.267757Z","iopub.status.idle":"2025-04-07T19:29:49.275754Z","shell.execute_reply.started":"2025-04-07T19:29:49.267701Z","shell.execute_reply":"2025-04-07T19:29:49.275039Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_train = y_train_multi\ny_val = y_val_multi","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:29:58.816725Z","iopub.execute_input":"2025-04-07T19:29:58.817043Z","iopub.status.idle":"2025-04-07T19:29:58.820643Z","shell.execute_reply.started":"2025-04-07T19:29:58.816977Z","shell.execute_reply":"2025-04-07T19:29:58.819615Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# delete the uneeded df\ndel new_train\ndel old_train\ndel val_df\ngc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:30:02.11748Z","iopub.execute_input":"2025-04-07T19:30:02.117766Z","iopub.status.idle":"2025-04-07T19:30:02.134361Z","shell.execute_reply.started":"2025-04-07T19:30:02.117713Z","shell.execute_reply":"2025-04-07T19:30:02.133184Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Creating keras callback for QWK\n\n---\n\nI had to change this function, in order to consider the best kappa score among all the buckets.","metadata":{}},{"cell_type":"code","source":"class Metrics(Callback):\n\n    def on_epoch_end(self, epoch, logs={}):\n        X_val, y_val = self.validation_data[:2]\n        y_val = y_val.sum(axis=1) - 1\n        \n        y_pred = self.model.predict(X_val) > 0.5\n        y_pred = y_pred.astype(int).sum(axis=1) - 1\n\n        _val_kappa = cohen_kappa_score(\n            y_val,\n            y_pred, \n            weights='quadratic'\n        )\n\n        self.val_kappas.append(_val_kappa)\n\n        print(f\"val_kappa: {_val_kappa:.4f}\")\n        \n        if _val_kappa == max(self.val_kappas):\n            print(\"Validation Kappa has improved. Saving model.\")\n            self.model.save('model.h5')\n\n        return","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:30:05.366897Z","iopub.execute_input":"2025-04-07T19:30:05.367242Z","iopub.status.idle":"2025-04-07T19:30:05.373648Z","shell.execute_reply.started":"2025-04-07T19:30:05.367189Z","shell.execute_reply":"2025-04-07T19:30:05.372682Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Data Generator","metadata":{}},{"cell_type":"code","source":"def create_datagen():\n    return ImageDataGenerator(\n        featurewise_std_normalization = True,\n        horizontal_flip = True,\n        vertical_flip = True,\n        rotation_range = 360\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:30:07.739827Z","iopub.execute_input":"2025-04-07T19:30:07.740156Z","iopub.status.idle":"2025-04-07T19:30:07.744385Z","shell.execute_reply.started":"2025-04-07T19:30:07.740099Z","shell.execute_reply":"2025-04-07T19:30:07.743494Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"resnet = ResNet50(\n    weights='/kaggle/input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5',\n    include_top=False,\n    input_shape=(im_size,im_size,3)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:30:10.399074Z","iopub.execute_input":"2025-04-07T19:30:10.399387Z","iopub.status.idle":"2025-04-07T19:30:18.959302Z","shell.execute_reply.started":"2025-04-07T19:30:10.399335Z","shell.execute_reply":"2025-04-07T19:30:18.958628Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Dropout, GlobalAveragePooling2D, Input\n\ndef build_model(input_shape=(224, 224, 3), num_classes=5):\n    base_model = ResNet50(include_top=False, weights='/kaggle/input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', input_shape=(im_size,im_size,3))\n    base_model.trainable = False  # Freeze the base model\n\n    inputs = Input(shape=input_shape)\n    x = base_model(inputs, training=False)\n    x = GlobalAveragePooling2D()(x)\n    x = Dropout(0.5)(x)\n    outputs = Dense(num_classes, activation='softmax')(x)\n\n    model = Model(inputs, outputs)\n    return model\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:30:28.864019Z","iopub.execute_input":"2025-04-07T19:30:28.864305Z","iopub.status.idle":"2025-04-07T19:30:28.871091Z","shell.execute_reply.started":"2025-04-07T19:30:28.864265Z","shell.execute_reply":"2025-04-07T19:30:28.870062Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = build_model()\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:30:31.650051Z","iopub.execute_input":"2025-04-07T19:30:31.650319Z","iopub.status.idle":"2025-04-07T19:30:41.555783Z","shell.execute_reply.started":"2025-04-07T19:30:31.650281Z","shell.execute_reply":"2025-04-07T19:30:41.554885Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Training & Evaluation","metadata":{}},{"cell_type":"code","source":"#train_df = train_df.reset_index(drop=True)\nbucket_num = 8\ndiv = round(train_df.shape[0]/bucket_num)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:30:47.598198Z","iopub.execute_input":"2025-04-07T19:30:47.5985Z","iopub.status.idle":"2025-04-07T19:30:47.60257Z","shell.execute_reply.started":"2025-04-07T19:30:47.598458Z","shell.execute_reply":"2025-04-07T19:30:47.60167Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_init = {\n    'val_loss': [0.0],\n    'val_acc': [0.0],\n    'loss': [0.0], \n    'acc': [0.0],\n    'bucket': [0.0]\n}\nresults = pd.DataFrame(df_init)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:30:54.713833Z","iopub.execute_input":"2025-04-07T19:30:54.714216Z","iopub.status.idle":"2025-04-07T19:30:54.719754Z","shell.execute_reply.started":"2025-04-07T19:30:54.714153Z","shell.execute_reply":"2025-04-07T19:30:54.718848Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# I found that changing the nr. of epochs for each bucket helped in terms of performances\nepochs = [5,5,10,15,15,20,20,30]\nkappa_metrics = Metrics(validation_data=(x_val_resized, y_val))\nkappa_metrics.val_kappas = []","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:35:21.677857Z","iopub.execute_input":"2025-04-07T19:35:21.678169Z","iopub.status.idle":"2025-04-07T19:35:21.682735Z","shell.execute_reply.started":"2025-04-07T19:35:21.678126Z","shell.execute_reply":"2025-04-07T19:35:21.681669Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(0,bucket_num):\n    if i != (bucket_num-1):\n        print(\"Bucket Nr: {}\".format(i))\n        \n        N = train_df.iloc[i*div:(1+i)*div].shape[0]\n        x_train = np.empty((N, im_size, im_size, 3), dtype=np.uint8)\n        for j, image_id in enumerate(tqdm_notebook(train_df.iloc[i*div:(1+i)*div,0])):\n            x_train[j, :, :, :] = preprocess_image_old(f'{image_id}', desired_size = im_size)\n\n        data_generator = create_datagen().flow(x_train, y_train[i*div:(1+i)*div,:], batch_size=BATCH_SIZE)\n        history = model.fit_generator(\n                        data_generator,\n                        steps_per_epoch=x_train.shape[0] / BATCH_SIZE,\n                        epochs=epochs[i],\n                        validation_data=(x_val, y_val),\n                        callbacks=[kappa_metrics]\n                        )\n        \n        dic = history.history\n        df_model = pd.DataFrame(dic)\n        df_model['bucket'] = i\n    else:\n        print(\"Bucket Nr: {}\".format(i))\n        \n        N = train_df.iloc[i*div:].shape[0]\n        x_train = np.empty((N, im_size, im_size, 3), dtype=np.uint8)\n        for j, image_id in enumerate(tqdm_notebook(train_df.iloc[i*div:,0])):\n            x_train[j, :, :, :] = preprocess_image_old(f'{image_id}', desired_size = im_size)\n        data_generator = create_datagen().flow(x_train, y_train[i*div:,:], batch_size=BATCH_SIZE)\n        \n        history = model.fit_generator(\n                        data_generator,\n                        steps_per_epoch=x_train.shape[0] / BATCH_SIZE,\n                        epochs=epochs[i],\n                        validation_data=(x_val, y_val),\n                        callbacks=[kappa_metrics]\n                        )\n        \n        dic = history.history\n        df_model = pd.DataFrame(dic)\n        df_model['bucket'] = i\n\n    results = results.append(df_model)\n    \n    del data_generator\n    del x_train\n    gc.collect()\n    \n    print('-'*40)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:36:23.931645Z","iopub.execute_input":"2025-04-07T19:36:23.93197Z","iopub.status.idle":"2025-04-07T21:39:45.404598Z","shell.execute_reply.started":"2025-04-07T19:36:23.931893Z","shell.execute_reply":"2025-04-07T21:39:45.403785Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"kappa_metrics = Metrics(validation_data=(x_val, y_val))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:27:29.865954Z","iopub.execute_input":"2025-04-07T19:27:29.866216Z","iopub.status.idle":"2025-04-07T19:27:29.869961Z","shell.execute_reply.started":"2025-04-07T19:27:29.866179Z","shell.execute_reply":"2025-04-07T19:27:29.869173Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results = results.iloc[1:]\nresults['kappa'] = kappa_metrics.val_kappas\nresults = results.reset_index()\nresults = results.rename(index=str, columns={\"index\": \"epoch\"})\nresults","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:27:08.392046Z","iopub.execute_input":"2025-04-07T19:27:08.392311Z","iopub.status.idle":"2025-04-07T19:27:08.404015Z","shell.execute_reply.started":"2025-04-07T19:27:08.39227Z","shell.execute_reply":"2025-04-07T19:27:08.403313Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results['loss'] = pd.to_numeric(results['loss'], errors='coerce')\nresults['val_loss'] = pd.to_numeric(results['val_loss'], errors='coerce')\nresults['acc'] = pd.to_numeric(results['acc'], errors='coerce')\nresults['val_acc'] = pd.to_numeric(results['val_acc'], errors='coerce')\nresults['kappa'] = pd.to_numeric(results['kappa'], errors='coerce')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:22:49.678841Z","iopub.execute_input":"2025-04-07T19:22:49.679173Z","iopub.status.idle":"2025-04-07T19:22:49.694175Z","shell.execute_reply.started":"2025-04-07T19:22:49.679117Z","shell.execute_reply":"2025-04-07T19:22:49.693279Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save_weights('model.h5')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:23:50.356874Z","iopub.execute_input":"2025-04-07T19:23:50.35723Z","iopub.status.idle":"2025-04-07T19:23:52.515659Z","shell.execute_reply.started":"2025-04-07T19:23:50.357182Z","shell.execute_reply":"2025-04-07T19:23:52.514763Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Find best threshold","metadata":{}},{"cell_type":"code","source":"model.load_weights('model.h5')\ny_val_pred = model.predict(x_val)\n\ndef compute_score_inv(threshold):\n    y1 = y_val_pred > threshold\n    y1 = y1.astype(int).sum(axis=1) - 1\n    y2 = y_val.sum(axis=1) - 1\n    score = cohen_kappa_score(y1, y2, weights='quadratic')\n    \n    return 1 - score\n\nsimplex = scipy.optimize.minimize(\n    compute_score_inv, 0.5, method='nelder-mead'\n)\n\nbest_threshold = simplex['x'][0]\n\ny1 = y_val_pred > best_threshold\ny1 = y1.astype(int).sum(axis=1) - 1\ny2 = y_val.sum(axis=1) - 1\nscore = cohen_kappa_score(y1, y2, weights='quadratic')\nprint('Threshold: {}'.format(best_threshold))\nprint('Validation QWK score with best_threshold: {}'.format(score))\n\ny1 = y_val_pred > .5\ny1 = y1.astype(int).sum(axis=1) - 1\nscore = cohen_kappa_score(y1, y2, weights='quadratic')\nprint('Validation QWK score with .5 threshold: {}'.format(score))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-07T19:23:59.748539Z","iopub.execute_input":"2025-04-07T19:23:59.748824Z","iopub.status.idle":"2025-04-07T19:24:12.060689Z","shell.execute_reply.started":"2025-04-07T19:23:59.748783Z","shell.execute_reply":"2025-04-07T19:24:12.059819Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## [Inference Kernel](https://www.kaggle.com/raimonds1993/aptos19-densenet-inference-old-new-data/data?scriptVersionId=17252732)\n\n**Thanks for reading it all! Please let me know if you have any ideas to improve this process.**\n\n**Hope you liked it.**","metadata":{}}]}