{"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":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# =========================================================\n# 1️⃣ Gerekli kütüphaneler\n# =========================================================\nimport os, zipfile, shutil\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import layers, models\nfrom sklearn.metrics import confusion_matrix, classification_report","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-09-26T12:07:05.869805Z","iopub.execute_input":"2025-09-26T12:07:05.870284Z","iopub.status.idle":"2025-09-26T12:07:05.877866Z","shell.execute_reply.started":"2025-09-26T12:07:05.870256Z","shell.execute_reply":"2025-09-26T12:07:05.876655Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =========================================================\n# 2️⃣ Zip dosyalarını aç\n# =========================================================\ndataset_path = '/kaggle/input/dogs-vs-cats'\n\n# Çalışma dizini: /kaggle/working\nextract_path = '/kaggle/working/dogs-vs-cats'\nos.makedirs(extract_path, exist_ok=True)\n\nwith zipfile.ZipFile(os.path.join(dataset_path,'train.zip'),'r') as zip_ref:\n    zip_ref.extractall(extract_path)\n\nwith zipfile.ZipFile(os.path.join(dataset_path,'test1.zip'),'r') as zip_ref:\n    zip_ref.extractall(extract_path)\n\nprint(\"Zip dosyaları açıldı.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T12:07:11.301258Z","iopub.execute_input":"2025-09-26T12:07:11.301594Z","iopub.status.idle":"2025-09-26T12:07:27.658858Z","shell.execute_reply.started":"2025-09-26T12:07:11.301566Z","shell.execute_reply":"2025-09-26T12:07:27.657771Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os, shutil\nimport zipfile\nfrom tqdm import tqdm\n\n# 1️⃣ ZIP dosyalarını aç\ninput_path = '/kaggle/input/dogs-vs-cats'\nwork_path  = '/kaggle/working/dogs-vs-cats'\nos.makedirs(work_path, exist_ok=True)\n\n# Sadece ilk çalıştırmada unzip yap\nif not os.path.exists(os.path.join(work_path, 'train')):\n    with zipfile.ZipFile(os.path.join(input_path, 'train.zip'), 'r') as z:\n        z.extractall(work_path)\n    with zipfile.ZipFile(os.path.join(input_path, 'test1.zip'), 'r') as z:\n        z.extractall(work_path)\n\n# 2️⃣ Klasör yollarını tanımla\ntrain_original = os.path.join(work_path, 'train')\ntrain_dir = os.path.join(work_path, 'train_split')\ncat_dir = os.path.join(train_dir, 'cat')\ndog_dir = os.path.join(train_dir, 'dog')\n\n# 3️⃣ Hücre tekrar çalıştırılırsa eski klasörleri sil\nshutil.rmtree(train_dir, ignore_errors=True)\nos.makedirs(cat_dir)\nos.makedirs(dog_dir)\n\n# 4️⃣ Sadece dosyaları uygun klasöre taşı\nfor fname in tqdm(os.listdir(train_original)):\n    src = os.path.join(train_original, fname)\n    if not os.path.isfile(src):   # klasör değilse\n        continue\n    if fname.startswith('cat'):\n        shutil.move(src, os.path.join(cat_dir, fname))\n    elif fname.startswith('dog'):\n        shutil.move(src, os.path.join(dog_dir, fname))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T12:07:33.532851Z","iopub.execute_input":"2025-09-26T12:07:33.533279Z","iopub.status.idle":"2025-09-26T12:07:35.641076Z","shell.execute_reply.started":"2025-09-26T12:07:33.533251Z","shell.execute_reply":"2025-09-26T12:07:35.639837Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    validation_split=0.2)  # %20 validation\n\ntrain_gen = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150,150),\n    batch_size=32,\n    class_mode='binary',\n    subset='training')\n\nval_gen = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150,150),\n    batch_size=32,\n    class_mode='binary',\n    subset='validation')\n\n# Örnek görselleri inceleme\nx_batch, y_batch = next(train_gen)\nplt.figure(figsize=(8,8))\nfor i in range(9):\n    plt.subplot(3,3,i+1)\n    plt.imshow(x_batch[i])\n    plt.axis('off')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T12:07:39.909727Z","iopub.execute_input":"2025-09-26T12:07:39.910100Z","iopub.status.idle":"2025-09-26T12:07:40.948605Z","shell.execute_reply.started":"2025-09-26T12:07:39.910073Z","shell.execute_reply":"2025-09-26T12:07:40.947239Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import layers, models\n\nmodel = models.Sequential([\n    layers.Conv2D(32,(3,3),activation='relu',input_shape=(150,150,3)),\n    layers.MaxPooling2D(2,2),\n    layers.Conv2D(64,(3,3),activation='relu'),\n    layers.MaxPooling2D(2,2),\n    layers.Conv2D(128,(3,3),activation='relu'),\n    layers.MaxPooling2D(2,2),\n    layers.Dropout(0.5),\n    layers.Flatten(),\n    layers.Dense(512,activation='relu'),\n    layers.Dense(1,activation='sigmoid')\n])\n\nmodel.compile(optimizer='adam',\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\n\nhistory = model.fit(\n    train_gen,\n    epochs=15,\n    validation_data=val_gen\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T12:07:49.152438Z","iopub.execute_input":"2025-09-26T12:07:49.152783Z","iopub.status.idle":"2025-09-26T15:15:57.988601Z","shell.execute_reply.started":"2025-09-26T12:07:49.152758Z","shell.execute_reply":"2025-09-26T15:15:57.984708Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['accuracy'], label='train acc')\nplt.plot(history.history['val_accuracy'], label='val acc')\nplt.legend()\nplt.title('Accuracy')\nplt.show()\n\nplt.plot(history.history['loss'], label='train loss')\nplt.plot(history.history['val_loss'], label='val loss')\nplt.legend()\nplt.title('Loss')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T15:16:10.149026Z","iopub.execute_input":"2025-09-26T15:16:10.149770Z","iopub.status.idle":"2025-09-26T15:16:10.672727Z","shell.execute_reply.started":"2025-09-26T15:16:10.149631Z","shell.execute_reply":"2025-09-26T15:16:10.670733Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, classification_report\nimport numpy as np\n\nval_gen.reset()\npreds = (model.predict(val_gen) > 0.5).astype(\"int32\")\n\nprint(confusion_matrix(val_gen.classes, preds))\nprint(classification_report(val_gen.classes, preds))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T15:16:19.432430Z","iopub.execute_input":"2025-09-26T15:16:19.432762Z","iopub.status.idle":"2025-09-26T15:17:22.206599Z","shell.execute_reply.started":"2025-09-26T15:16:19.432738Z","shell.execute_reply":"2025-09-26T15:17:22.205293Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np, cv2, matplotlib.pyplot as plt, tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing import image\n\ndef grad_cam(model, img_path, last_conv_layer_name=\"conv2d_5\",\n             pred_index=None, image_size=(150,150), alpha=0.4):\n    # ---- 1. Görüntü hazırla\n    img = image.load_img(img_path, target_size=image_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0) / 255.0\n\n    # ---- 2. Bir kez tahmin al\n    preds = model.predict(img_array)\n    if pred_index is None:\n        pred_index = 0   # binary için tek nöron var\n    class_output = preds[:, pred_index]\n\n    # ---- 3. Grad model: son conv + model çıkışı\n    grad_model = keras.models.Model(\n        [model.input],\n        [model.get_layer(last_conv_layer_name).output,\n         model.layers[-1].output]\n    )\n\n    with tf.GradientTape() as tape:\n        conv_outputs, predictions = grad_model(img_array)\n        loss = predictions[:, pred_index]\n\n    grads = tape.gradient(loss, conv_outputs)\n    pooled_grads = tf.reduce_mean(grads, axis=(0,1,2))\n    conv_outputs = conv_outputs[0]\n    heatmap = tf.reduce_sum(tf.multiply(pooled_grads, conv_outputs), axis=-1)\n    heatmap = np.maximum(heatmap,0) / (np.max(heatmap)+1e-10)\n\n    img0 = cv2.imread(img_path)\n    img0 = cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)\n    heatmap = cv2.resize(heatmap.numpy(), (img0.shape[1], img0.shape[0]))\n    heatmap = np.uint8(255*heatmap)\n    heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)\n    overlay = cv2.addWeighted(img0, 1-alpha, heatmap, alpha, 0)\n    return heatmap, overlay\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T15:23:46.828335Z","iopub.execute_input":"2025-09-26T15:23:46.828638Z","iopub.status.idle":"2025-09-26T15:23:46.839587Z","shell.execute_reply.started":"2025-09-26T15:23:46.828616Z","shell.execute_reply":"2025-09-26T15:23:46.838415Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Daha kısa örnek: learning rate değişimi\nfrom tensorflow.keras.optimizers import Adam\n\nfor lr in [1e-4, 1e-3]:\n    print(f\"\\n--- Learning rate: {lr} ---\")\n    model_lr = models.clone_model(model)\n    model_lr.compile(optimizer=Adam(learning_rate=lr),\n                     loss='binary_crossentropy',\n                     metrics=['accuracy'])\n    model_lr.fit(train_gen, epochs=3, validation_data=val_gen)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-26T15:30:25.854848Z","iopub.execute_input":"2025-09-26T15:30:25.855286Z","iopub.status.idle":"2025-09-26T16:45:20.096321Z","shell.execute_reply.started":"2025-09-26T15:30:25.855259Z","shell.execute_reply":"2025-09-26T16:45:20.095160Z"}},"outputs":[],"execution_count":null}]}