{"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":5441,"databundleVersionId":38425,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":false,"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-09-26T17:27:52.194518Z","iopub.execute_input":"2025-09-26T17:27:52.194862Z","iopub.status.idle":"2025-09-26T17:27:52.202249Z","shell.execute_reply.started":"2025-09-26T17:27:52.194837Z","shell.execute_reply":"2025-09-26T17:27:52.201279Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Dogs vs Cats - CNN ile Görüntü Sınıflandırma\nBu projede, kediler 🐱 ve köpekler 🐶 arasındaki görselleri sınıflandırmak için Convolutional Neural Network (CNN) tabanlı bir derin öğrenme modeli geliştirdim.\n","metadata":{}},{"cell_type":"markdown","source":"🐱🐶 Cats vs Dogs Sınıflandırma + Grad-CAM Notebook\n📌 1. Kütüphaneler ve Ayarlar","metadata":{}},{"cell_type":"code","source":"import os\nimport zipfile\nimport shutil\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization\nfrom tensorflow.keras.optimizers import Adam\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n# TensorFlow loglarını sessize al\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T17:27:52.203615Z","iopub.execute_input":"2025-09-26T17:27:52.203945Z","iopub.status.idle":"2025-09-26T17:27:52.219792Z","shell.execute_reply.started":"2025-09-26T17:27:52.203923Z","shell.execute_reply":"2025-09-26T17:27:52.218879Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"📌 2. Veri Hazırlığı\n\nZip dosyası açılır\n\nResimler cat/ ve dog/ klasörlerine taşınır","metadata":{}},{"cell_type":"code","source":"train_zip = \"/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\"\nwith zipfile.ZipFile(train_zip, 'r') as zip_ref:\n    zip_ref.extractall(\"/kaggle/working/train\")\n\n# Klasörler\nbase_dir = \"/kaggle/working/cats_vs_dogs\"\ncat_dir = os.path.join(base_dir, \"cat\")\ndog_dir = os.path.join(base_dir, \"dog\")\nos.makedirs(cat_dir, exist_ok=True)\nos.makedirs(dog_dir, exist_ok=True)\n\n# Resimleri taşı\nsrc_dir = \"/kaggle/working/train/train\"\nfor fname in os.listdir(src_dir):\n    if fname.startswith(\"cat\"):\n        shutil.copy(os.path.join(src_dir, fname), cat_dir)\n    elif fname.startswith(\"dog\"):\n        shutil.copy(os.path.join(src_dir, fname), dog_dir)\n\nprint(\"Toplam cat resmi:\", len(os.listdir(cat_dir)))\nprint(\"Toplam dog resmi:\", len(os.listdir(dog_dir)))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T17:27:52.494526Z","iopub.execute_input":"2025-09-26T17:27:52.494904Z","iopub.status.idle":"2025-09-26T17:28:05.231441Z","shell.execute_reply.started":"2025-09-26T17:27:52.494874Z","shell.execute_reply":"2025-09-26T17:28:05.230507Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"📌 3. Data Augmentation ve Generator\n\nEğitim verileri artırma teknikleri\n\nTrain/Validation ayrımı","metadata":{}},{"cell_type":"code","source":"img_size = (64,64)\nbatch_size = 32\n\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    validation_split=0.2,\n    rotation_range=20,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    shear_range=0.1,\n    zoom_range=0.1,\n    horizontal_flip=True\n)\n\ntrain_generator = train_datagen.flow_from_directory(\n    base_dir,\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_directory(\n    base_dir,\n    target_size=img_size,\n    batch_size=batch_size,\n    class_mode='binary',\n    subset='validation',\n    shuffle=False\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T17:28:05.232718Z","iopub.execute_input":"2025-09-26T17:28:05.233136Z","iopub.status.idle":"2025-09-26T17:28:05.566313Z","shell.execute_reply.started":"2025-09-26T17:28:05.233110Z","shell.execute_reply":"2025-09-26T17:28:05.565382Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"📌 4. CNN Modeli (Functional API)\n\nConv2D + BatchNormalization + Dropout\n\nDaha güçlü özellik çıkarımı","metadata":{}},{"cell_type":"code","source":"inputs = Input(shape=(64,64,3))\n\nx = Conv2D(32, (3,3), activation='relu', padding=\"same\", name=\"conv1\")(inputs)\nx = BatchNormalization()(x)\nx = MaxPooling2D(2,2)(x)\n\nx = Conv2D(64, (3,3), activation='relu', padding=\"same\", name=\"conv2\")(x)\nx = BatchNormalization()(x)\nx = MaxPooling2D(2,2)(x)\n\nx = Conv2D(128, (3,3), activation='relu', padding=\"same\", name=\"conv3\")(x)\nx = BatchNormalization()(x)\nx = MaxPooling2D(2,2)(x)\n\nx = Conv2D(256, (3,3), activation='relu', padding=\"same\", name=\"conv4\")(x)\nx = BatchNormalization()(x)\nx = MaxPooling2D(2,2)(x)\n\nx = Flatten()(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.5)(x)\noutputs = Dense(1, activation='sigmoid')(x)\n\nmodel = Model(inputs, outputs)\nmodel.compile(optimizer=Adam(1e-4), loss='binary_crossentropy', metrics=['accuracy'])\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T17:28:05.567578Z","iopub.execute_input":"2025-09-26T17:28:05.567833Z","iopub.status.idle":"2025-09-26T17:28:05.708942Z","shell.execute_reply.started":"2025-09-26T17:28:05.567814Z","shell.execute_reply":"2025-09-26T17:28:05.708090Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"📌 5. Eğitim (Callback Eklenmiş)\n\nEarlyStopping → aşırı öğrenmeyi önler\n\nReduceLROnPlateau → val_loss düşmezse öğrenme oranını azaltır","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\n\nearly_stop = EarlyStopping(monitor=\"val_loss\", patience=5, restore_best_weights=True)\nreduce_lr = ReduceLROnPlateau(monitor=\"val_loss\", factor=0.3, patience=3, verbose=1)\n\nhistory = model.fit(\n    train_generator,\n    validation_data=val_generator,\n    epochs=5,\n    callbacks=[early_stop, reduce_lr]\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T17:28:05.710616Z","iopub.execute_input":"2025-09-26T17:28:05.710875Z","iopub.status.idle":"2025-09-26T17:43:43.775348Z","shell.execute_reply.started":"2025-09-26T17:28:05.710854Z","shell.execute_reply":"2025-09-26T17:43:43.773966Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"📌 6. Accuracy ve Loss Grafikleri","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(12,5))\nplt.subplot(1,2,1)\nplt.plot(history.history['accuracy'], label='Train Acc')\nplt.plot(history.history['val_accuracy'], label='Val Acc')\nplt.title('Accuracy')\nplt.legend()\n\nplt.subplot(1,2,2)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Val Loss')\nplt.title('Loss')\nplt.legend()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T17:43:43.777302Z","iopub.execute_input":"2025-09-26T17:43:43.777629Z","iopub.status.idle":"2025-09-26T17:43:44.202595Z","shell.execute_reply.started":"2025-09-26T17:43:43.777592Z","shell.execute_reply":"2025-09-26T17:43:44.201609Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"📌 7. Confusion Matrix ve Rapor","metadata":{}},{"cell_type":"code","source":"val_generator.reset()\nY_pred = model.predict(val_generator, verbose=1)\ny_pred = np.round(Y_pred).astype(int)\ny_true = val_generator.classes\n\ncm = confusion_matrix(y_true, y_pred)\nplt.figure(figsize=(6,6))\nsns.heatmap(cm, annot=True, fmt=\"d\", cmap='Blues')\nplt.xlabel('Tahmin')\nplt.ylabel('Gerçek')\nplt.title('Confusion Matrix')\nplt.show()\n\nprint(classification_report(y_true, y_pred, target_names=['Cat','Dog']))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T17:43:44.203688Z","iopub.execute_input":"2025-09-26T17:43:44.204107Z","iopub.status.idle":"2025-09-26T17:44:02.933939Z","shell.execute_reply.started":"2025-09-26T17:43:44.204081Z","shell.execute_reply":"2025-09-26T17:44:02.933005Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"📌 8. Grad-CAM\n\nGörselde modelin hangi bölgeye odaklandığını gösterir","metadata":{}},{"cell_type":"code","source":"def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):\n    grad_model = tf.keras.models.Model(\n        [model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]\n    )\n    with tf.GradientTape() as tape:\n        conv_outputs, predictions = grad_model(img_array)\n        if pred_index is None:\n            pred_index = tf.argmax(predictions[0])\n        class_channel = predictions[:, pred_index]\n    grads = tape.gradient(class_channel, conv_outputs)\n    pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))\n    conv_outputs = conv_outputs[0]\n    heatmap = conv_outputs @ pooled_grads[..., tf.newaxis]\n    heatmap = tf.squeeze(heatmap)\n    heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)\n    return heatmap.numpy()\n\ndef display_gradcam(img_array, heatmap, pred_label, true_label, confidence, alpha=0.4):\n    import cv2\n    heatmap = np.uint8(255 * heatmap)\n    jet = plt.colormaps[\"jet\"]\n    jet_colors = jet(np.arange(256))[:, :3]\n    jet_heatmap = jet_colors[heatmap]\n    jet_heatmap = tf.image.resize(jet_heatmap, (img_array.shape[1], img_array.shape[2]))\n    superimposed_img = jet_heatmap * alpha + img_array[0]\n    superimposed_img = np.clip(superimposed_img, 0, 1)\n    plt.figure(figsize=(4,4))\n    plt.imshow(superimposed_img)\n    plt.axis('off')\n    plt.title(f\"Gerçek: {true_label} | Tahmin: {pred_label} ({confidence:.2f})\")\n    plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T17:44:02.934983Z","iopub.execute_input":"2025-09-26T17:44:02.935278Z","iopub.status.idle":"2025-09-26T17:44:02.946391Z","shell.execute_reply.started":"2025-09-26T17:44:02.935256Z","shell.execute_reply":"2025-09-26T17:44:02.945351Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"📌 9. Grad-CAM Uygulaması","metadata":{}},{"cell_type":"code","source":"class_names = ['Cat','Dog']\n\nval_images, val_labels = next(iter(val_generator))\n_ = model.predict(val_images[:1])  # tensorları başlat\n\nlast_conv_layer_name = \"conv3\"\n\nfor i in range(5):\n    img_array = np.expand_dims(val_images[i], axis=0)\n    heatmap = make_gradcam_heatmap(img_array, model, last_conv_layer_name)\n    pred_prob = model.predict(img_array, verbose=0)[0][0]\n    pred_class = 1 if pred_prob > 0.5 else 0\n    pred_label = class_names[pred_class]\n    true_label = class_names[int(val_labels[i])]\n    display_gradcam(img_array, heatmap, pred_label, true_label, pred_prob)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T17:44:02.947485Z","iopub.execute_input":"2025-09-26T17:44:02.947832Z","iopub.status.idle":"2025-09-26T17:44:04.675805Z","shell.execute_reply.started":"2025-09-26T17:44:02.947807Z","shell.execute_reply":"2025-09-26T17:44:04.674895Z"}},"outputs":[],"execution_count":null}]}