{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"competition","sourceId":5441,"databundleVersionId":38425}],"dockerImageVersionId":31329,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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":"2026-04-22T11:47:11.695080Z","iopub.execute_input":"2026-04-22T11:47:11.696047Z","iopub.status.idle":"2026-04-22T11:47:12.009040Z","shell.execute_reply.started":"2026-04-22T11:47:11.696021Z","shell.execute_reply":"2026-04-22T11:47:12.008211Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Importing Libraries","metadata":{}},{"cell_type":"code","source":"# Standart Kütüphaneler\nimport os\nimport math\nimport zipfile\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Veri İşleme\nimport numpy as np\nimport pandas as pd\n\n# Görselleştirme\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Görüntü İşleme\nimport cv2\nfrom PIL import Image\n\n# Makine Öğrenmesi (sklearn)\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, accuracy_score\n\n# TensorFlow / Keras\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.models import Sequential, load_model\nfrom tensorflow.keras.layers import (\n    Dense,\n    Conv2D,\n    Flatten,\n    Input,\n    MaxPooling2D,\n    Dropout,\n    BatchNormalization,\n    Reshape\n)\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.layers import GlobalAveragePooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:12.011473Z","iopub.execute_input":"2026-04-22T11:47:12.011925Z","iopub.status.idle":"2026-04-22T11:47:34.593155Z","shell.execute_reply.started":"2026-04-22T11:47:12.011901Z","shell.execute_reply":"2026-04-22T11:47:34.592479Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Loading and Organizing Data","metadata":{}},{"cell_type":"code","source":"data_dir = '/kaggle/input/competitions/dogs-vs-cats-redux-kernels-edition/'\n\n# Zip dosyalarını çıkartmak için hedef dizin\nextract_dir = '/kaggle/working/'\n\ntrain_zip = os.path.join(data_dir, 'train.zip')\ntest_zip  = os.path.join(data_dir, 'test.zip')\n\n# Train zip'i çıkart\nwith zipfile.ZipFile(train_zip, 'r') as zf:\n    zf.extractall(extract_dir)\n\n# Test zip'i çıkart\nwith zipfile.ZipFile(test_zip, 'r') as zf:\n    zf.extractall(extract_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:34.594007Z","iopub.execute_input":"2026-04-22T11:47:34.594410Z","iopub.status.idle":"2026-04-22T11:47:47.342492Z","shell.execute_reply.started":"2026-04-22T11:47:34.594387Z","shell.execute_reply":"2026-04-22T11:47:47.341861Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Güncel path'ler\ntrain_path = os.path.join(extract_dir, 'train')\ntest_path  = os.path.join(extract_dir, 'test')\n\nprint(\"Train path:\", train_path)\nprint(\"Test path:\", test_path)\nprint(\"Train dosya sayısı:\", len(os.listdir(train_path)))\nprint(\"Test dosya sayısı:\", len(os.listdir(test_path)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:47.343499Z","iopub.execute_input":"2026-04-22T11:47:47.343887Z","iopub.status.idle":"2026-04-22T11:47:47.369321Z","shell.execute_reply.started":"2026-04-22T11:47:47.343860Z","shell.execute_reply":"2026-04-22T11:47:47.368489Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_img_list = []\ntrain_label_list = []\n\n# Train klasöründeki tüm dosyaları dolaş\nfor img_file in os.listdir(train_path):\n    if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n        img_full_path = os.path.join(train_path, img_file)\n        if os.path.isfile(img_full_path):\n            # Dosya adından label'ı çıkar: \"cat.0.jpg\" -> \"cat\", \"dog.0.jpg\" -> \"dog\"\n            label = img_file.split('.')[0]  # 'cat' veya 'dog'\n            train_img_list.append(img_full_path)\n            train_label_list.append(label)\n\ntrain_df = pd.DataFrame({'img': train_img_list, 'label': train_label_list})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:47.370355Z","iopub.execute_input":"2026-04-22T11:47:47.370695Z","iopub.status.idle":"2026-04-22T11:47:47.524521Z","shell.execute_reply.started":"2026-04-22T11:47:47.370662Z","shell.execute_reply":"2026-04-22T11:47:47.523866Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:47.525533Z","iopub.execute_input":"2026-04-22T11:47:47.525963Z","iopub.status.idle":"2026-04-22T11:47:47.554168Z","shell.execute_reply.started":"2026-04-22T11:47:47.525925Z","shell.execute_reply":"2026-04-22T11:47:47.553545Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# CNN için label'ı sayısala çevirelim cat -> 0, dog -> 1\ntrain_df['label_encoded'] = train_df['label'].map({'cat': 0, 'dog': 1})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:47.555028Z","iopub.execute_input":"2026-04-22T11:47:47.555363Z","iopub.status.idle":"2026-04-22T11:47:47.564934Z","shell.execute_reply.started":"2026-04-22T11:47:47.555339Z","shell.execute_reply":"2026-04-22T11:47:47.564105Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df.head(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:47.565994Z","iopub.execute_input":"2026-04-22T11:47:47.566355Z","iopub.status.idle":"2026-04-22T11:47:47.578944Z","shell.execute_reply.started":"2026-04-22T11:47:47.566331Z","shell.execute_reply":"2026-04-22T11:47:47.578050Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_img_list = []\ntest_id_list = []\n\nfor img_file in os.listdir(test_path):\n    if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n        img_full_path = os.path.join(test_path, img_file)\n        if os.path.isfile(img_full_path):\n            test_img_list.append(img_full_path)\n            test_id_list.append(int(img_file.split('.')[0]))  \n\ntest_df = pd.DataFrame({'id': test_id_list, 'img': test_img_list})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:47.579927Z","iopub.execute_input":"2026-04-22T11:47:47.580294Z","iopub.status.idle":"2026-04-22T11:47:47.666646Z","shell.execute_reply.started":"2026-04-22T11:47:47.580273Z","shell.execute_reply":"2026-04-22T11:47:47.666070Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df = test_df.sort_values('id').reset_index(drop=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:47.667414Z","iopub.execute_input":"2026-04-22T11:47:47.667786Z","iopub.status.idle":"2026-04-22T11:47:47.676379Z","shell.execute_reply.started":"2026-04-22T11:47:47.667753Z","shell.execute_reply":"2026-04-22T11:47:47.675694Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df.head(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:47.677250Z","iopub.execute_input":"2026-04-22T11:47:47.678176Z","iopub.status.idle":"2026-04-22T11:47:47.687888Z","shell.execute_reply.started":"2026-04-22T11:47:47.678135Z","shell.execute_reply":"2026-04-22T11:47:47.687012Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Visualition\nlabels = train_df['label'].unique()  # ['cat', 'dog']\nn_samples = 5  # her sınıftan kaç görsel yükleyeceğimizi belirtiyoruz\n\nfig, axes = plt.subplots(2, n_samples, figsize=(15, 6))\n\nfor row, label in enumerate(labels):\n    img_paths = train_df[train_df['label'] == label]['img'].sample(n_samples, random_state=42)\n    \n    for col, img_path in enumerate(img_paths):\n        image = Image.open(img_path)\n        axes[row, col].imshow(image)\n        axes[row, col].axis('off')\n        if col == 0:\n            axes[row, col].set_title(f'{\"🐱 Cat\" if label == \"cat\" else \"🐶 Dog\"}', \n                                      fontsize=13, fontweight='bold', loc='left')\n\nplt.suptitle('Dogs vs Cats - Sample Images', fontsize=16, fontweight='bold', y=1.02)\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:47.688959Z","iopub.execute_input":"2026-04-22T11:47:47.689293Z","iopub.status.idle":"2026-04-22T11:47:48.380363Z","shell.execute_reply.started":"2026-04-22T11:47:47.689270Z","shell.execute_reply":"2026-04-22T11:47:48.379406Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Normalizing","metadata":{}},{"cell_type":"code","source":"#  Görüntü Yükleme ve Normalizasyon \ndef load_image(img_path, img_size=(128, 128)):    \n    img = cv2.imread(str(img_path))\n\n    if img is None:\n        return None\n\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)    \n    img = cv2.resize(img, img_size)\n    img = img.astype(\"float32\") / 255.0           # Normalize [0, 1]\n\n    return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:48.383890Z","iopub.execute_input":"2026-04-22T11:47:48.384188Z","iopub.status.idle":"2026-04-22T11:47:48.391028Z","shell.execute_reply.started":"2026-04-22T11:47:48.384163Z","shell.execute_reply":"2026-04-22T11:47:48.390182Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#  DataFrame'den Toplu Yükleme Fonksiyonu \ndef load_dataset(df, has_label=True, log_step=5000):\n    images, labels = [], []\n\n    for idx, row in df.iterrows():\n        img = load_image(row['img'])\n        if img is not None:\n            images.append(img)\n            if has_label:\n                labels.append(row['label_encoded'])\n\n        if (idx + 1) % log_step == 0:\n            print(f\"  {idx + 1}/{len(df)} yüklendi.\")\n\n    images = np.array(images)\n    return (images, np.array(labels)) if has_label else images\n\n\nprint(\"Train verisi yükleniyor...\")\nx_train, y_train = load_dataset(train_df, has_label=True)\nprint(f\"✅ Train verisi : {x_train.shape}\")   \nprint(f\"✅ Label sayısı : {len(y_train)}\")    \n\n\nprint(\"\\nTest verisi yükleniyor...\")\nx_test = load_dataset(test_df, has_label=False)\nprint(f\"✅ Test verisi  : {x_test.shape}\")    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:47:48.391886Z","iopub.execute_input":"2026-04-22T11:47:48.392213Z","iopub.status.idle":"2026-04-22T11:48:51.551476Z","shell.execute_reply.started":"2026-04-22T11:47:48.392183Z","shell.execute_reply":"2026-04-22T11:48:51.550653Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Train / Validation Split","metadata":{}},{"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(\n    x_train, y_train,\n    test_size=0.2,\n    random_state=42,\n    stratify=y_train          \n)\nprint(f\"Train: {x_train.shape}, Validation: {x_val.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:48:51.552623Z","iopub.execute_input":"2026-04-22T11:48:51.552944Z","iopub.status.idle":"2026-04-22T11:48:53.011545Z","shell.execute_reply.started":"2026-04-22T11:48:51.552912Z","shell.execute_reply":"2026-04-22T11:48:53.010796Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## CNN Modeling","metadata":{}},{"cell_type":"code","source":"model = Sequential([\n\n    Input(shape=(128, 128, 3)),          \n\n    # Block 1\n    Conv2D(32, (3,3), padding=\"same\", activation='relu', kernel_regularizer=l2(0.001)),\n    BatchNormalization(),\n    MaxPooling2D((2,2)),\n    Dropout(0.25),\n\n    # Block 2\n    Conv2D(64, (3,3), padding=\"same\", activation='relu', kernel_regularizer=l2(0.001)),\n    BatchNormalization(),\n    MaxPooling2D((2,2)),\n    Dropout(0.25),\n\n    # Block 3\n    Conv2D(128, (3,3), padding=\"same\", activation='relu', kernel_regularizer=l2(0.001)),\n    BatchNormalization(),\n    MaxPooling2D((2,2)),\n    Dropout(0.3),\n\n    # Block 4 (128x128 için ek blok)\n    Conv2D(256, (3,3), padding=\"same\", activation='relu', kernel_regularizer=l2(0.001)),\n    BatchNormalization(),\n    MaxPooling2D((2,2)),\n    Dropout(0.3),\n\n    Flatten(),\n\n    Dense(256, activation='relu', kernel_regularizer=l2(0.001)),\n    BatchNormalization(),\n    Dropout(0.5),\n\n    Dense(1, activation='sigmoid')       #Binary: 0 cat, 1dog \n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:48:53.012659Z","iopub.execute_input":"2026-04-22T11:48:53.013029Z","iopub.status.idle":"2026-04-22T11:48:55.298123Z","shell.execute_reply.started":"2026-04-22T11:48:53.012997Z","shell.execute_reply":"2026-04-22T11:48:55.297154Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:48:55.299142Z","iopub.execute_input":"2026-04-22T11:48:55.299442Z","iopub.status.idle":"2026-04-22T11:48:55.312238Z","shell.execute_reply.started":"2026-04-22T11:48:55.299418Z","shell.execute_reply":"2026-04-22T11:48:55.311412Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:48:55.313261Z","iopub.execute_input":"2026-04-22T11:48:55.313654Z","iopub.status.idle":"2026-04-22T11:48:55.339907Z","shell.execute_reply.started":"2026-04-22T11:48:55.313621Z","shell.execute_reply":"2026-04-22T11:48:55.339298Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"callbacks = [\n    EarlyStopping(\n        monitor='val_loss',\n        patience=10,\n        restore_best_weights=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":"2026-04-22T11:48:55.343301Z","iopub.execute_input":"2026-04-22T11:48:55.343804Z","iopub.status.idle":"2026-04-22T11:48:55.348155Z","shell.execute_reply.started":"2026-04-22T11:48:55.343777Z","shell.execute_reply":"2026-04-22T11:48:55.347577Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Trainig\nhistory = model.fit(\n    x_train, y_train,\n    validation_data=(x_val, y_val),\n    epochs=30,\n    batch_size=32,\n    callbacks=callbacks,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:48:55.349159Z","iopub.execute_input":"2026-04-22T11:48:55.349573Z","iopub.status.idle":"2026-04-22T11:54:49.595554Z","shell.execute_reply.started":"2026-04-22T11:48:55.349541Z","shell.execute_reply":"2026-04-22T11:54:49.594836Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Saving the Model","metadata":{}},{"cell_type":"code","source":"model.save('dogs_vs_cats_cnn.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:54:49.596571Z","iopub.execute_input":"2026-04-22T11:54:49.596886Z","iopub.status.idle":"2026-04-22T11:54:49.762995Z","shell.execute_reply.started":"2026-04-22T11:54:49.596862Z","shell.execute_reply":"2026-04-22T11:54:49.762351Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('dogs_vs_cats_cnn.keras')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:54:49.765719Z","iopub.execute_input":"2026-04-22T11:54:49.765928Z","iopub.status.idle":"2026-04-22T11:54:50.030922Z","shell.execute_reply.started":"2026-04-22T11:54:49.765908Z","shell.execute_reply":"2026-04-22T11:54:50.030240Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Loss & Accuracy \nplt.figure(figsize=(15, 6))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'],     label='Train Loss',      color='#8502d1')\nplt.plot(history.history['val_loss'], label='Validation Loss', color='darkorange')\nplt.legend()\nplt.title('Loss Evolution')\nplt.xlabel('Epoch')\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['accuracy'],     label='Train Accuracy',      color='#8502d1')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy', color='darkorange')\nplt.legend()\nplt.title('Accuracy Evolution')\nplt.xlabel('Epoch')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:54:50.031877Z","iopub.execute_input":"2026-04-22T11:54:50.032180Z","iopub.status.idle":"2026-04-22T11:54:50.348305Z","shell.execute_reply.started":"2026-04-22T11:54:50.032150Z","shell.execute_reply":"2026-04-22T11:54:50.347628Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Predict on the Test","metadata":{}},{"cell_type":"code","source":"y_pred_prob     = model.predict(x_test)              \ny_pred_classes  = (y_pred_prob > 0.5).astype(int).flatten()  # 0=cat, 1=dog\nclass_names     = {0: '🐱 Cat', 1: '🐶 Dog'}\n\n# İlk 10 test görselini göster\nplt.figure(figsize=(15, 4))\nfor i in range(10):\n    plt.subplot(2, 5, i + 1)\n    plt.imshow(x_test[i])\n    plt.title(f\"{class_names[y_pred_classes[i]]}\\n({y_pred_prob[i][0]:.2f})\", fontsize=9)\n    plt.axis('off')\nplt.suptitle('İlk 10 Test Tahmini', fontweight='bold')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:54:50.349460Z","iopub.execute_input":"2026-04-22T11:54:50.349886Z","iopub.status.idle":"2026-04-22T11:55:00.024689Z","shell.execute_reply.started":"2026-04-22T11:54:50.349863Z","shell.execute_reply":"2026-04-22T11:55:00.023600Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Validation Confusion Matrix\ny_val_pred_prob    = model.predict(x_val)\ny_val_pred_classes = (y_val_pred_prob > 0.5).astype(int).flatten()\n\ncm_val = confusion_matrix(y_val, y_val_pred_classes)\n\nplt.figure(figsize=(6, 5))\nsns.heatmap(cm_val, annot=True, fmt='d', cmap='crest',\n            xticklabels=['Cat', 'Dog'],\n            yticklabels=['Cat', 'Dog'])\nplt.xlabel('Tahmin Edilen')\nplt.ylabel('Gerçek')\nplt.title('Confusion Matrix - Validation Seti')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:00.026099Z","iopub.execute_input":"2026-04-22T11:55:00.026461Z","iopub.status.idle":"2026-04-22T11:55:03.707475Z","shell.execute_reply.started":"2026-04-22T11:55:00.026424Z","shell.execute_reply":"2026-04-22T11:55:03.706665Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = pd.DataFrame({\n    'id':    test_df['id'],                  \n    'label': y_pred_prob.flatten()          \n})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:03.708612Z","iopub.execute_input":"2026-04-22T11:55:03.708939Z","iopub.status.idle":"2026-04-22T11:55:03.713883Z","shell.execute_reply.started":"2026-04-22T11:55:03.708916Z","shell.execute_reply":"2026-04-22T11:55:03.713245Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = submission.sort_values('id').reset_index(drop=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:03.714813Z","iopub.execute_input":"2026-04-22T11:55:03.715368Z","iopub.status.idle":"2026-04-22T11:55:03.727125Z","shell.execute_reply.started":"2026-04-22T11:55:03.715341Z","shell.execute_reply":"2026-04-22T11:55:03.726408Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.head(15)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:03.727877Z","iopub.execute_input":"2026-04-22T11:55:03.728191Z","iopub.status.idle":"2026-04-22T11:55:03.744283Z","shell.execute_reply.started":"2026-04-22T11:55:03.728160Z","shell.execute_reply":"2026-04-22T11:55:03.743461Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:03.745289Z","iopub.execute_input":"2026-04-22T11:55:03.745632Z","iopub.status.idle":"2026-04-22T11:55:03.781239Z","shell.execute_reply.started":"2026-04-22T11:55:03.745609Z","shell.execute_reply":"2026-04-22T11:55:03.780691Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Transfer Learning ","metadata":{}},{"cell_type":"code","source":"# Parameters\nIMG_SIZE   = (128, 128)\nBATCH_SIZE = 32\n\n# Data Generators \ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    validation_split=0.20,\n    rotation_range=20,\n    zoom_range=0.2,\n    horizontal_flip=True\n)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    x_col='img',\n    y_col='label',                 # cat or dog\n    target_size=IMG_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode='binary',            \n    subset='training',\n    shuffle=True\n)\n\nval_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    x_col='img',\n    y_col='label',\n    target_size=IMG_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode='binary',            \n    subset='validation',\n    shuffle=False                   \n)\n\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=test_df,\n    x_col='img',\n    target_size=IMG_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode=None,\n    shuffle=False\n)\n\nprint(f\"Train   : {train_generator.samples}\")\nprint(f\"Val     : {val_generator.samples}\")\nprint(f\"Test    : {test_generator.samples}\")\nprint(f\"Classes : {train_generator.class_indices}\")  # {'cat': 0, 'dog': 1}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:03.781951Z","iopub.execute_input":"2026-04-22T11:55:03.782228Z","iopub.status.idle":"2026-04-22T11:55:04.204778Z","shell.execute_reply.started":"2026-04-22T11:55:03.782194Z","shell.execute_reply":"2026-04-22T11:55:04.203905Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Transfer Learning - VGG16 \nbase_model = VGG16(\n    weights='imagenet',\n    input_shape=(*IMG_SIZE, 3),\n    include_top=False\n)\nbase_model.trainable = False       # Önceden eğitilmiş ağırlıkları dondurmak için FALSe diyoruz\n\nmodel = Sequential([\n    base_model,\n    GlobalAveragePooling2D(),\n    Dense(256, activation='relu'), \n    Dropout(0.5),\n    Dense(1, activation='sigmoid')\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:04.205909Z","iopub.execute_input":"2026-04-22T11:55:04.206213Z","iopub.status.idle":"2026-04-22T11:55:04.938803Z","shell.execute_reply.started":"2026-04-22T11:55:04.206191Z","shell.execute_reply":"2026-04-22T11:55:04.938128Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:04.939724Z","iopub.execute_input":"2026-04-22T11:55:04.940050Z","iopub.status.idle":"2026-04-22T11:55:04.948243Z","shell.execute_reply.started":"2026-04-22T11:55:04.940025Z","shell.execute_reply":"2026-04-22T11:55:04.947559Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:04.949107Z","iopub.execute_input":"2026-04-22T11:55:04.949460Z","iopub.status.idle":"2026-04-22T11:55:04.971620Z","shell.execute_reply.started":"2026-04-22T11:55:04.949434Z","shell.execute_reply":"2026-04-22T11:55:04.970712Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"callbacks = [\n    EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True, verbose=1),\n    ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3, min_lr=1e-7, verbose=1)\n]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:04.972604Z","iopub.execute_input":"2026-04-22T11:55:04.972963Z","iopub.status.idle":"2026-04-22T11:55:04.977268Z","shell.execute_reply.started":"2026-04-22T11:55:04.972931Z","shell.execute_reply":"2026-04-22T11:55:04.976558Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    train_generator,\n    epochs=20,\n    validation_data=val_generator,\n    callbacks=callbacks,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T11:55:04.978224Z","iopub.execute_input":"2026-04-22T11:55:04.978575Z","iopub.status.idle":"2026-04-22T12:26:45.805914Z","shell.execute_reply.started":"2026-04-22T11:55:04.978539Z","shell.execute_reply":"2026-04-22T12:26:45.804827Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('dogs_vs_cats_TL.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T12:26:45.807029Z","iopub.execute_input":"2026-04-22T12:26:45.807584Z","iopub.status.idle":"2026-04-22T12:26:45.926279Z","shell.execute_reply.started":"2026-04-22T12:26:45.807545Z","shell.execute_reply":"2026-04-22T12:26:45.925258Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('dogs_vs_cats_TL.keras')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T12:26:45.927272Z","iopub.execute_input":"2026-04-22T12:26:45.927594Z","iopub.status.idle":"2026-04-22T12:26:46.183966Z","shell.execute_reply.started":"2026-04-22T12:26:45.927570Z","shell.execute_reply":"2026-04-22T12:26:46.183036Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Loss & Accuracy\nplt.figure(figsize=(15, 6))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'],     label='Train Loss',      color='#8502d1')\nplt.plot(history.history['val_loss'], label='Validation Loss', color='darkorange')\nplt.legend()\nplt.title('Loss Evolution')\nplt.xlabel('Epoch')\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['accuracy'],     label='Train Accuracy',      color='#8502d1')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy', color='darkorange')\nplt.legend()\nplt.title('Accuracy Evolution')\nplt.xlabel('Epoch')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-22T12:26:46.185042Z","iopub.execute_input":"2026-04-22T12:26:46.185333Z","iopub.status.idle":"2026-04-22T12:26:46.515257Z","shell.execute_reply.started":"2026-04-22T12:26:46.185301Z","shell.execute_reply":"2026-04-22T12:26:46.514564Z"}},"outputs":[],"execution_count":null}]}