{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.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":8089,"databundleVersionId":44321,"sourceType":"competition"}],"dockerImageVersionId":31153,"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-29T11:59:36.719360Z","iopub.execute_input":"2025-10-29T11:59:36.719656Z","iopub.status.idle":"2025-10-29T11:59:38.817877Z","shell.execute_reply.started":"2025-10-29T11:59:36.719629Z","shell.execute_reply":"2025-10-29T11:59:38.816982Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nimport os\nimport sys\nimport random\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom itertools import chain\nfrom skimage.io import imread, imshow, imread_collection, concatenate_images\nfrom skimage.transform import resize\nfrom skimage.morphology import label\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, models\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:00:14.117959Z","iopub.execute_input":"2025-10-29T12:00:14.118594Z","iopub.status.idle":"2025-10-29T12:00:31.078846Z","shell.execute_reply.started":"2025-10-29T12:00:14.118552Z","shell.execute_reply":"2025-10-29T12:00:31.077876Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import zipfile\nTRAIN_ZIP = '/kaggle/input/data-science-bowl-2018/stage1_train.zip'\nTEST_ZIP = '/kaggle/input/data-science-bowl-2018/stage1_test.zip'\n# Directory where to extract\nTRAIN_PATH = '/kaggle/working/stage1_train/'\nTEST_PATH = '/kaggle/working/stage1_test/'\n\n# Unzip the train data\nwith zipfile.ZipFile(TRAIN_ZIP, 'r') as zip_ref:\n    zip_ref.extractall(TRAIN_PATH)\n\n# Unzip the test data\nwith zipfile.ZipFile(TEST_ZIP, 'r') as zip_ref:\n    zip_ref.extractall(TEST_PATH)\n\nprint(\"Extraction complete!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:04:53.603776Z","iopub.execute_input":"2025-10-29T12:04:53.605328Z","iopub.status.idle":"2025-10-29T12:04:58.271491Z","shell.execute_reply.started":"2025-10-29T12:04:53.605294Z","shell.execute_reply":"2025-10-29T12:04:58.270545Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"SEED = 42\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntf.random.set_seed(SEED)\n\n# Constants\nIMG_WIDTH = 256\nIMG_HEIGHT = 256\nIMG_CHANNELS = 3\nTRAIN_PATH = 'stage1_train/'\nTEST_PATH = 'stage1_test/'\n\nwarnings.filterwarnings('ignore', category=UserWarning, module='skimage')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:05:48.562662Z","iopub.execute_input":"2025-10-29T12:05:48.563475Z","iopub.status.idle":"2025-10-29T12:05:48.568618Z","shell.execute_reply.started":"2025-10-29T12:05:48.563449Z","shell.execute_reply":"2025-10-29T12:05:48.567647Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_ids = next(os.walk(TRAIN_PATH))[1]\nX_train = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)\nY_train = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, 1), dtype=np.float32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:05:49.672651Z","iopub.execute_input":"2025-10-29T12:05:49.672955Z","iopub.status.idle":"2025-10-29T12:05:49.679269Z","shell.execute_reply.started":"2025-10-29T12:05:49.672935Z","shell.execute_reply":"2025-10-29T12:05:49.678424Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f'Getting and resizing {len(train_ids)} images and masks ... ')\nsys.stdout.flush()\n\nfor n, id_ in tqdm(enumerate(train_ids), total=len(train_ids)):\n    path = TRAIN_PATH + id_\n    img = imread(path + '/images/' + id_ + '.png')[:, :, :IMG_CHANNELS]\n    img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode='constant', preserve_range=True)\n    X_train[n] = img\n    \n    # Load and combine all masks for this image\n    mask = np.zeros((IMG_HEIGHT, IMG_WIDTH, 1), dtype=np.float32)\n    for mask_file in next(os.walk(path + '/masks/'))[2]:\n        mask_ = imread(path + '/masks/' + mask_file)\n        mask_ = np.expand_dims(resize(mask_, (IMG_HEIGHT, IMG_WIDTH), \n                                     mode='constant', preserve_range=True), axis=-1)\n        mask = np.maximum(mask, mask_)\n    \n    # Normalize mask to 0-1 range\n    if mask.max() > 1.0:\n        mask = mask / 255.0\n    \n    Y_train[n] = mask\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:06:04.677720Z","iopub.execute_input":"2025-10-29T12:06:04.678664Z","iopub.status.idle":"2025-10-29T12:11:06.859621Z","shell.execute_reply.started":"2025-10-29T12:06:04.678622Z","shell.execute_reply":"2025-10-29T12:11:06.858366Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Normalize images\nX_train = X_train / 255.0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:29.111979Z","iopub.execute_input":"2025-10-29T12:13:29.112385Z","iopub.status.idle":"2025-10-29T12:13:30.244306Z","shell.execute_reply.started":"2025-10-29T12:13:29.112361Z","shell.execute_reply":"2025-10-29T12:13:30.243331Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Split into train and validation\nX_train, X_val, Y_train, Y_val = train_test_split(\n    X_train, Y_train, test_size=0.15, random_state=SEED\n)\nprint(f'Train set: {X_train.shape}')\nprint(f'Validation set: {X_val.shape}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:31.175700Z","iopub.execute_input":"2025-10-29T12:13:31.176004Z","iopub.status.idle":"2025-10-29T12:13:32.227722Z","shell.execute_reply.started":"2025-10-29T12:13:31.175983Z","shell.execute_reply":"2025-10-29T12:13:32.226890Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Input layer\ninputs = layers.Input(shape=(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:33.888960Z","iopub.execute_input":"2025-10-29T12:13:33.889718Z","iopub.status.idle":"2025-10-29T12:13:33.895036Z","shell.execute_reply.started":"2025-10-29T12:13:33.889691Z","shell.execute_reply":"2025-10-29T12:13:33.894197Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# Encoder block 1\nc1 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(inputs)\nc1 = layers.Dropout(0.2)(c1)\nc1 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(c1)\np1 = layers.MaxPooling2D((2, 2))(c1)\n\n# Encoder block 2\nc2 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(p1)\nc2 = layers.Dropout(0.2)(c2)\nc2 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(c2)\np2 = layers.MaxPooling2D((2, 2))(c2)\n\n# Encoder block 3\nc3 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(p2)\nc3 = layers.Dropout(0.2)(c3)\nc3 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(c3)\np3 = layers.MaxPooling2D((2, 2))(c3)\n\n# Encoder block 4\nc4 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(p3)\nc4 = layers.Dropout(0.2)(c4)\nc4 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(c4)\np4 = layers.MaxPooling2D((2, 2))(c4)\n\n# Bridge\nc5 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(p4)\nc5 = layers.Dropout(0.2)(c5)\nc5 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(c5)\n\n# Decoder block 1\nu6 = layers.Conv2DTranspose(128, (2, 2), strides=2, padding='same')(c5)\nu6 = layers.Concatenate()([u6, c4])\nc6 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(u6)\nc6 = layers.Dropout(0.2)(c6)\nc6 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(c6)\n\n# Decoder block 2\nu7 = layers.Conv2DTranspose(64, (2, 2), strides=2, padding='same')(c6)\nu7 = layers.Concatenate()([u7, c3])\nc7 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(u7)\nc7 = layers.Dropout(0.2)(c7)\nc7 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(c7)\n\n# Decoder block 3\nu8 = layers.Conv2DTranspose(32, (2, 2), strides=2, padding='same')(c7)\nu8 = layers.Concatenate()([u8, c2])\nc8 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(u8)\nc8 = layers.Dropout(0.2)(c8)\nc8 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(c8)\n\n# Decoder block 4\nu9 = layers.Conv2DTranspose(16, (2, 2), strides=2, padding='same')(c8)\nu9 = layers.Concatenate()([u9, c1])\nc9 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(u9)\nc9 = layers.Dropout(0.2)(c9)\nc9 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(c9)\n\n# Output layer\noutputs = layers.Conv2D(1, (1, 1), activation='sigmoid')(c9)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:35.240344Z","iopub.execute_input":"2025-10-29T12:13:35.240979Z","iopub.status.idle":"2025-10-29T12:13:35.572424Z","shell.execute_reply.started":"2025-10-29T12:13:35.240955Z","shell.execute_reply":"2025-10-29T12:13:35.571632Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create model\nmodel = models.Model(inputs=[inputs], outputs=[outputs], name='U-Net')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:41.031299Z","iopub.execute_input":"2025-10-29T12:13:41.032237Z","iopub.status.idle":"2025-10-29T12:13:41.041250Z","shell.execute_reply.started":"2025-10-29T12:13:41.032203Z","shell.execute_reply":"2025-10-29T12:13:41.040288Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Dice coefficient metric\ndef dice_coefficient(y_true, y_pred, smooth=1e-6):\n    y_true_f = tf.cast(tf.keras.backend.flatten(y_true), tf.float32)\n    y_pred_f = tf.cast(tf.keras.backend.flatten(y_pred), tf.float32)\n    intersection = tf.keras.backend.sum(y_true_f * y_pred_f)\n    return (2. * intersection + smooth) / (tf.keras.backend.sum(y_true_f) + \n                                           tf.keras.backend.sum(y_pred_f) + smooth)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:42.095048Z","iopub.execute_input":"2025-10-29T12:13:42.095359Z","iopub.status.idle":"2025-10-29T12:13:42.100977Z","shell.execute_reply.started":"2025-10-29T12:13:42.095339Z","shell.execute_reply":"2025-10-29T12:13:42.100032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# Dice loss\ndef dice_loss(y_true, y_pred):\n    return 1 - dice_coefficient(y_true, y_pred)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:43.516701Z","iopub.execute_input":"2025-10-29T12:13:43.517501Z","iopub.status.idle":"2025-10-29T12:13:43.521545Z","shell.execute_reply.started":"2025-10-29T12:13:43.517473Z","shell.execute_reply":"2025-10-29T12:13:43.520663Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Combined BCE + Dice loss\ndef bce_dice_loss(y_true, y_pred):\n    bce = tf.keras.losses.binary_crossentropy(y_true, y_pred)\n    return bce + dice_loss(y_true, y_pred)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:46.190770Z","iopub.execute_input":"2025-10-29T12:13:46.191088Z","iopub.status.idle":"2025-10-29T12:13:46.196270Z","shell.execute_reply.started":"2025-10-29T12:13:46.191068Z","shell.execute_reply":"2025-10-29T12:13:46.195295Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# IoU metric\ndef iou_metric(y_true, y_pred, smooth=1e-6):\n    y_true_f = tf.cast(tf.keras.backend.flatten(y_true), tf.float32)\n    y_pred_f = tf.cast(tf.keras.backend.flatten(y_pred), tf.float32)\n    intersection = tf.keras.backend.sum(y_true_f * y_pred_f)\n    union = tf.keras.backend.sum(y_true_f) + tf.keras.backend.sum(y_pred_f) - intersection\n    return (intersection + smooth) / (union + smooth)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:47.147734Z","iopub.execute_input":"2025-10-29T12:13:47.148402Z","iopub.status.idle":"2025-10-29T12:13:47.153989Z","shell.execute_reply.started":"2025-10-29T12:13:47.148373Z","shell.execute_reply":"2025-10-29T12:13:47.152596Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile model\nmodel.compile(\n    optimizer=keras.optimizers.Adam(learning_rate=1e-4),\n    loss=bce_dice_loss,\n    metrics=[dice_coefficient, iou_metric, 'accuracy']\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:49.820251Z","iopub.execute_input":"2025-10-29T12:13:49.821079Z","iopub.status.idle":"2025-10-29T12:13:49.836700Z","shell.execute_reply.started":"2025-10-29T12:13:49.821047Z","shell.execute_reply":"2025-10-29T12:13:49.835819Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:50.874160Z","iopub.execute_input":"2025-10-29T12:13:50.874471Z","iopub.status.idle":"2025-10-29T12:13:50.929784Z","shell.execute_reply.started":"2025-10-29T12:13:50.874451Z","shell.execute_reply":"2025-10-29T12:13:50.929017Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# Setup callbacks\ncallbacks = [\n    EarlyStopping(\n        monitor='val_loss',\n        patience=10,\n        verbose=1,\n        restore_best_weights=True\n    ),\n    ModelCheckpoint(\n        'best_model.h5',\n        monitor='val_dice_coefficient',\n        mode='max',\n        save_best_only=True,\n        verbose=1\n    ),\n    ReduceLROnPlateau(\n        monitor='val_loss',\n        factor=0.5,\n        patience=5,\n        min_lr=1e-7,\n        verbose=1\n    )\n]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:58.117546Z","iopub.execute_input":"2025-10-29T12:13:58.118462Z","iopub.status.idle":"2025-10-29T12:13:58.123230Z","shell.execute_reply.started":"2025-10-29T12:13:58.118433Z","shell.execute_reply":"2025-10-29T12:13:58.122351Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train the model\nhistory = model.fit(\n    X_train, Y_train,\n    validation_data=(X_val, Y_val),\n    batch_size=16,\n    epochs=50,\n    callbacks=callbacks,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T12:13:59.617006Z","iopub.execute_input":"2025-10-29T12:13:59.617280Z","iopub.status.idle":"2025-10-29T15:07:18.873965Z","shell.execute_reply.started":"2025-10-29T12:13:59.617261Z","shell.execute_reply":"2025-10-29T15:07:18.873219Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nfig, axes = plt.subplots(2, 2, figsize=(15, 10))\n\n# Loss\naxes[0, 0].plot(history.history['loss'], label='Train Loss', linewidth=2)\naxes[0, 0].plot(history.history['val_loss'], label='Val Loss', linewidth=2)\naxes[0, 0].set_title('Model Loss', fontsize=14, fontweight='bold')\naxes[0, 0].set_xlabel('Epoch')\naxes[0, 0].set_ylabel('Loss')\naxes[0, 0].legend()\naxes[0, 0].grid(True, alpha=0.3)\n\n# Dice Coefficient\naxes[0, 1].plot(history.history['dice_coefficient'], label='Train Dice', linewidth=2)\naxes[0, 1].plot(history.history['val_dice_coefficient'], label='Val Dice', linewidth=2)\naxes[0, 1].set_title('Dice Coefficient', fontsize=14, fontweight='bold')\naxes[0, 1].set_xlabel('Epoch')\naxes[0, 1].set_ylabel('Dice Coefficient')\naxes[0, 1].legend()\naxes[0, 1].grid(True, alpha=0.3)\n\n# IoU\naxes[1, 0].plot(history.history['iou_metric'], label='Train IoU', linewidth=2)\naxes[1, 0].plot(history.history['val_iou_metric'], label='Val IoU', linewidth=2)\naxes[1, 0].set_title('IoU Metric', fontsize=14, fontweight='bold')\naxes[1, 0].set_xlabel('Epoch')\naxes[1, 0].set_ylabel('IoU')\naxes[1, 0].legend()\naxes[1, 0].grid(True, alpha=0.3)\n\n# Accuracy\naxes[1, 1].plot(history.history['accuracy'], label='Train Acc', linewidth=2)\naxes[1, 1].plot(history.history['val_accuracy'], label='Val Acc', linewidth=2)\naxes[1, 1].set_title('Accuracy', fontsize=14, fontweight='bold')\naxes[1, 1].set_xlabel('Epoch')\naxes[1, 1].set_ylabel('Accuracy')\naxes[1, 1].legend()\naxes[1, 1].grid(True, alpha=0.3)\n\nplt.tight_layout()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T15:19:48.083499Z","iopub.execute_input":"2025-10-29T15:19:48.083882Z","iopub.status.idle":"2025-10-29T15:19:49.196597Z","shell.execute_reply.started":"2025-10-29T15:19:48.083855Z","shell.execute_reply":"2025-10-29T15:19:49.195645Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"\\nGenerating predictions on validation set...\")\nY_val_pred = model.predict(X_val, verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T15:19:52.994906Z","iopub.execute_input":"2025-10-29T15:19:52.995231Z","iopub.status.idle":"2025-10-29T15:20:03.936616Z","shell.execute_reply.started":"2025-10-29T15:19:52.995208Z","shell.execute_reply":"2025-10-29T15:20:03.935832Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# Visualize some predictions\nprint(\"\\nVisualizing predictions...\")\nnum_samples = 5\nfig, axes = plt.subplots(num_samples, 3, figsize=(12, 4*num_samples))\n\nfor i in range(num_samples):\n    idx = random.randint(0, len(X_val)-1)\n    \n    axes[i, 0].imshow(X_val[idx])\n    axes[i, 0].set_title('Original Image', fontsize=12, fontweight='bold')\n    axes[i, 0].axis('off')\n    \n    axes[i, 1].imshow(np.squeeze(Y_val[idx]), cmap='gray')\n    axes[i, 1].set_title('True Mask', fontsize=12, fontweight='bold')\n    axes[i, 1].axis('off')\n    \n    axes[i, 2].imshow(np.squeeze(Y_val_pred[idx]), cmap='gray')\n    axes[i, 2].set_title('Predicted Mask', fontsize=12, fontweight='bold')\n    axes[i, 2].axis('off')\n\nplt.tight_layout()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T15:20:03.945906Z","iopub.execute_input":"2025-10-29T15:20:03.946602Z","iopub.status.idle":"2025-10-29T15:20:06.003137Z","shell.execute_reply.started":"2025-10-29T15:20:03.946552Z","shell.execute_reply":"2025-10-29T15:20:06.001753Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_ids = next(os.walk(TEST_PATH))[1]\nX_test = np.zeros((len(test_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)\nsizes_test = []\n\nprint(f'Loading {len(test_ids)} test images...')\n\nfor n, id_ in tqdm(enumerate(test_ids), total=len(test_ids)):\n    path = TEST_PATH + id_\n    img = imread(path + '/images/' + id_ + '.png')[:, :, :IMG_CHANNELS]\n    sizes_test.append([img.shape[0], img.shape[1]])\n    img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode='constant', preserve_range=True)\n    X_test[n] = img\n    \n# Normalize\nX_test = X_test / 255.0\n\n# Predict \npreds_test = model.predict(X_test, verbose=1)\n\n# Threshold predictions - try multiple thresholds\nthreshold = 0.5\npreds_test_t = (preds_test > threshold).astype(np.uint8)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T15:20:22.215928Z","iopub.execute_input":"2025-10-29T15:20:22.216277Z","iopub.status.idle":"2025-10-29T15:20:30.573990Z","shell.execute_reply.started":"2025-10-29T15:20:22.216255Z","shell.execute_reply":"2025-10-29T15:20:30.572942Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Run-length encoding function\ndef rle_encode(img):\n    pixels = img.flatten()\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n\n# Convert predictions to RLE\nnew_test_ids = []\nrles = []\n\nprint(\"Encoding predictions...\")\nfor n, id_ in tqdm(enumerate(test_ids), total=len(test_ids)):\n    # Get prediction and squeeze to 2D\n    pred = preds_test_t[n].squeeze()\n    \n    # Label each connected component (each nucleus)\n    lab_img = label(pred)\n    \n    # If no nuclei detected, add empty prediction\n    if lab_img.max() == 0:\n        new_test_ids.append(id_)\n        rles.append('')\n    else:\n        # Encode each nucleus separately\n        for i in range(1, lab_img.max() + 1):\n            nucleus_mask = (lab_img == i).astype(np.uint8)\n            rle = rle_encode(nucleus_mask)\n            rles.append(rle)\n            new_test_ids.append(id_)\n\n# Create submission DataFrame\nsub = pd.DataFrame()\nsub['ImageId'] = new_test_ids\nsub['EncodedPixels'] = rles\nsub.to_csv('submission.csv', index=False)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T15:20:30.575274Z","iopub.execute_input":"2025-10-29T15:20:30.575600Z","iopub.status.idle":"2025-10-29T15:20:30.956354Z","shell.execute_reply.started":"2025-10-29T15:20:30.575554Z","shell.execute_reply":"2025-10-29T15:20:30.955464Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T15:20:58.665709Z","iopub.execute_input":"2025-10-29T15:20:58.666323Z","iopub.status.idle":"2025-10-29T15:20:58.692203Z","shell.execute_reply.started":"2025-10-29T15:20:58.666297Z","shell.execute_reply":"2025-10-29T15:20:58.691328Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}