{"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":"gpu","dataSources":[{"sourceId":8089,"databundleVersionId":44321,"sourceType":"competition"}],"dockerImageVersionId":31193,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"\nimport numpy as np  \nimport pandas as pd  \n\nimport os\nimport sys\nimport random\nimport warnings  \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\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n ","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:03:59.031919Z","iopub.execute_input":"2025-12-02T06:03:59.032466Z","iopub.status.idle":"2025-12-02T06:03:59.041149Z","shell.execute_reply.started":"2025-12-02T06:03:59.03244Z","shell.execute_reply":"2025-12-02T06:03:59.040458Z"}},"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/stage2_test_final.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-12-02T06:03:59.04219Z","iopub.execute_input":"2025-12-02T06:03:59.042528Z","iopub.status.idle":"2025-12-02T06:04:05.620084Z","shell.execute_reply.started":"2025-12-02T06:03:59.042508Z","shell.execute_reply":"2025-12-02T06:04:05.619368Z"}},"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-12-02T06:04:05.620822Z","iopub.execute_input":"2025-12-02T06:04:05.621093Z","iopub.status.idle":"2025-12-02T06:04:05.625867Z","shell.execute_reply.started":"2025-12-02T06:04:05.621073Z","shell.execute_reply":"2025-12-02T06:04:05.625147Z"}},"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-12-02T06:04:05.627573Z","iopub.execute_input":"2025-12-02T06:04:05.627807Z","iopub.status.idle":"2025-12-02T06:04:06.017075Z","shell.execute_reply.started":"2025-12-02T06:04:05.62779Z","shell.execute_reply":"2025-12-02T06:04:06.016446Z"}},"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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:04:06.017764Z","iopub.execute_input":"2025-12-02T06:04:06.018005Z","iopub.status.idle":"2025-12-02T06:08:08.373251Z","shell.execute_reply.started":"2025-12-02T06:04:06.017985Z","shell.execute_reply":"2025-12-02T06:08:08.372661Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Normalize images\nX_train = X_train / 255.0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:08:08.373984Z","iopub.execute_input":"2025-12-02T06:08:08.374232Z","iopub.status.idle":"2025-12-02T06:08:08.722816Z","shell.execute_reply.started":"2025-12-02T06:08:08.374192Z","shell.execute_reply":"2025-12-02T06:08:08.722009Z"}},"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) ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:08:08.723752Z","iopub.execute_input":"2025-12-02T06:08:08.724042Z","iopub.status.idle":"2025-12-02T06:08:09.097158Z","shell.execute_reply.started":"2025-12-02T06:08:08.724018Z","shell.execute_reply":"2025-12-02T06:08:09.096588Z"}},"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-12-02T06:08:09.097855Z","iopub.execute_input":"2025-12-02T06:08:09.098031Z","iopub.status.idle":"2025-12-02T06:08:09.10312Z","shell.execute_reply.started":"2025-12-02T06:08:09.098016Z","shell.execute_reply":"2025-12-02T06:08:09.102403Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:08:09.103737Z","iopub.execute_input":"2025-12-02T06:08:09.103948Z","iopub.status.idle":"2025-12-02T06:08:11.200415Z","shell.execute_reply.started":"2025-12-02T06:08:09.103926Z","shell.execute_reply":"2025-12-02T06:08:11.199862Z"}},"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-12-02T06:08:11.203008Z","iopub.execute_input":"2025-12-02T06:08:11.203268Z","iopub.status.idle":"2025-12-02T06:08:11.209975Z","shell.execute_reply.started":"2025-12-02T06:08:11.203252Z","shell.execute_reply":"2025-12-02T06:08:11.209292Z"}},"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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:08:11.210833Z","iopub.execute_input":"2025-12-02T06:08:11.211095Z","iopub.status.idle":"2025-12-02T06:08:11.228434Z","shell.execute_reply.started":"2025-12-02T06:08:11.211071Z","shell.execute_reply":"2025-12-02T06:08:11.227757Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Dice loss\ndef dice_loss(y_true, y_pred):\n    return 1 - dice_coefficient(y_true, y_pred)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:08:11.229143Z","iopub.execute_input":"2025-12-02T06:08:11.229327Z","iopub.status.idle":"2025-12-02T06:08:11.244074Z","shell.execute_reply.started":"2025-12-02T06:08:11.229312Z","shell.execute_reply":"2025-12-02T06:08:11.243353Z"}},"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-12-02T06:08:11.244832Z","iopub.execute_input":"2025-12-02T06:08:11.245054Z","iopub.status.idle":"2025-12-02T06:08:11.262341Z","shell.execute_reply.started":"2025-12-02T06:08:11.245027Z","shell.execute_reply":"2025-12-02T06:08:11.261652Z"}},"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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:08:11.263047Z","iopub.execute_input":"2025-12-02T06:08:11.263233Z","iopub.status.idle":"2025-12-02T06:08:11.27667Z","shell.execute_reply.started":"2025-12-02T06:08:11.263218Z","shell.execute_reply":"2025-12-02T06:08:11.276013Z"}},"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-12-02T06:08:11.277424Z","iopub.execute_input":"2025-12-02T06:08:11.277669Z","iopub.status.idle":"2025-12-02T06:08:11.30102Z","shell.execute_reply.started":"2025-12-02T06:08:11.277646Z","shell.execute_reply":"2025-12-02T06:08:11.300451Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:08:11.301744Z","iopub.execute_input":"2025-12-02T06:08:11.301993Z","iopub.status.idle":"2025-12-02T06:08:11.348183Z","shell.execute_reply.started":"2025-12-02T06:08:11.301969Z","shell.execute_reply":"2025-12-02T06:08:11.347622Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:08:11.348927Z","iopub.execute_input":"2025-12-02T06:08:11.349163Z","iopub.status.idle":"2025-12-02T06:08:11.353072Z","shell.execute_reply.started":"2025-12-02T06:08:11.349146Z","shell.execute_reply":"2025-12-02T06:08:11.352423Z"}},"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-12-02T06:08:11.353902Z","iopub.execute_input":"2025-12-02T06:08:11.354139Z","iopub.status.idle":"2025-12-02T06:11:20.226208Z","shell.execute_reply.started":"2025-12-02T06:08:11.35412Z","shell.execute_reply":"2025-12-02T06:11:20.225558Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig, 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-12-02T06:11:20.234471Z","iopub.execute_input":"2025-12-02T06:11:20.234728Z","iopub.status.idle":"2025-12-02T06:11:21.190246Z","shell.execute_reply.started":"2025-12-02T06:11:20.234708Z","shell.execute_reply":"2025-12-02T06:11:21.18949Z"}},"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-12-02T06:11:21.191055Z","iopub.execute_input":"2025-12-02T06:11:21.191289Z","iopub.status.idle":"2025-12-02T06:11:26.679693Z","shell.execute_reply.started":"2025-12-02T06:11:21.191264Z","shell.execute_reply":"2025-12-02T06:11:26.67886Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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-12-02T06:11:26.6807Z","iopub.execute_input":"2025-12-02T06:11:26.681062Z","iopub.status.idle":"2025-12-02T06:11:28.354851Z","shell.execute_reply.started":"2025-12-02T06:11:26.681038Z","shell.execute_reply":"2025-12-02T06:11:28.353841Z"}},"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\nfrom skimage.color import gray2rgb # Bu satırı en başa eklemeyi unutmayın\n\n# ... diğer kodlar ...\n\nprint(f'Loading {len(test_ids)} test images...')\nfor n, id_ in tqdm(enumerate(test_ids), total=len(test_ids)):\n    path = TEST_PATH + id_\n    \n    # 1. Resmi ham haliyle yükle (dilimleme yapmadan)\n    img = imread(path + '/images/' + id_ + '.png')\n    \n    # 2. HATA DÜZELTME: Eğer resim 2 boyutluysa (siyah-beyaz), RGB'ye çevir\n    if len(img.shape) == 2:\n        img = gray2rgb(img)\n    \n    # 3. Şimdi kanal sayısını ayarlayabilirsin (Alpha kanalını atmak için)\n    img = img[:, :, :IMG_CHANNELS]\n    \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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:11:28.356011Z","iopub.execute_input":"2025-12-02T06:11:28.356775Z","iopub.status.idle":"2025-12-02T06:13:14.308494Z","shell.execute_reply.started":"2025-12-02T06:11:28.35674Z","shell.execute_reply":"2025-12-02T06:13:14.307816Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from skimage.transform import resize\n\n# RLE Encode Fonksiyonu (Kaggle formatı için Transpose eklendi)\ndef rle_encode(img):\n    # Kaggle genellikle sütun bazlı (column-major) tarama ister, bu yüzden .T (transpose) ekliyoruz\n    pixels = img.T.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\nnew_test_ids = []\nrles = []\n\nprint(\"Tahminler işleniyor ve orijinal boyutlara dönüştürülüyor...\")\n\nfor n, id_ in tqdm(enumerate(test_ids), total=len(test_ids)):\n    # 1. Tahmini al (256x256)\n    pred_mask = preds_test[n] \n    \n    # 2. Orijinal boyutuna geri döndür (Cell 22'de kaydettiğiniz sizes_test listesini kullanarak)\n    original_height, original_width = sizes_test[n]\n    \n    # Resize işlemi (maske olduğu için order=0 veya anti-aliasing kapalı olabilir ama \n    # sigmoid çıktısı olduğu için default resize sonrası threshold yapmak iyidir)\n    resized_mask = resize(pred_mask, (original_height, original_width), mode='constant', preserve_range=True)\n    \n    # 3. Threshold uygula (0.5 eşik değeri)\n    binary_mask = (resized_mask > 0.5).astype(np.uint8)\n    \n    # 4. Labeling ve RLE\n    # Not: Bu yarışmada her çekirdek (nucleus) ayrı bir satır mı yoksa hepsi tek satır mı isteniyor?\n    # Genelde Semantic Segmentation'da tek satır istenir, Instance'da çok satır.\n    # Data Science Bowl 2018 Instance Segmentation'dır, yani her hücre ayrı satır olmalı.\n    \n    lab_img = label(binary_mask)\n    \n    if lab_img.max() == 0:\n        new_test_ids.append(id_)\n        rles.append('')\n    else:\n        # Her bir çekirdeği (nucleus) ayrı ayrı encode et\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# Submission dosyasını oluştur\nsub = pd.DataFrame()\nsub['ImageId'] = new_test_ids\nsub['EncodedPixels'] = rles\n\n# Dosyayı kaydet\nsub.to_csv('submission.csv', index=False)\nprint(\"submission.csv başarıyla oluşturuldu!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:13:14.309454Z","iopub.execute_input":"2025-12-02T06:13:14.309936Z","iopub.status.idle":"2025-12-02T06:14:34.180305Z","shell.execute_reply.started":"2025-12-02T06:13:14.309915Z","shell.execute_reply":"2025-12-02T06:14:34.179626Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T06:14:34.18116Z","iopub.execute_input":"2025-12-02T06:14:34.181484Z","iopub.status.idle":"2025-12-02T06:14:34.200447Z","shell.execute_reply.started":"2025-12-02T06:14:34.181458Z","shell.execute_reply":"2025-12-02T06:14:34.199702Z"}},"outputs":[],"execution_count":null}]}