{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30786,"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":"2024-11-07T12:39:17.055427Z","iopub.execute_input":"2024-11-07T12:39:17.056179Z","iopub.status.idle":"2024-11-07T12:39:18.098010Z","shell.execute_reply.started":"2024-11-07T12:39:17.056133Z","shell.execute_reply":"2024-11-07T12:39:18.097035Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Gerekli kütüphanelerin bazılarını yükleyelim.\n\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport cv2\n\nfrom PIL import Image\n\nfrom sklearn.metrics import classification_report\n\nfrom keras import layers\nfrom keras import models\nfrom keras import optimizers\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array, ImageDataGenerator\nfrom keras import applications\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nimport zipfile\n\nimport glob\nimport os\nprint(\"Cats&Dogs Dataset Klasör içeriği:\",os.listdir(\"../input\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:18.099905Z","iopub.execute_input":"2024-11-07T12:39:18.100427Z","iopub.status.idle":"2024-11-07T12:39:30.693284Z","shell.execute_reply.started":"2024-11-07T12:39:18.100381Z","shell.execute_reply":"2024-11-07T12:39:30.692310Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Dataları zip dosyasından çıkartalım.\n\nzip_files = ['train','test1']\n# Dosyaları görebilmeniz için sıkıştırılmış dosyaları açacağız.\nfor zip_file in zip_files:\n    with zipfile.ZipFile(\"../input/dogs-vs-cats/{}.zip\".format(zip_file),\"r\") as z:\n        z.extractall(\".\")\n        print(\"{} unzipped\".format(zip_file))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:30.694515Z","iopub.execute_input":"2024-11-07T12:39:30.695112Z","iopub.status.idle":"2024-11-07T12:39:44.353502Z","shell.execute_reply.started":"2024-11-07T12:39:30.695074Z","shell.execute_reply":"2024-11-07T12:39:44.352541Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Görüntü dosyalarını kontrol edelim.\n\ntrain_dir = '/kaggle/working/train'\n\ntrain_images = os.listdir(train_dir)\n\nprint(f\"Toplam Eğitim Görüntüsü Sayısı: {len(train_images)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:44.355730Z","iopub.execute_input":"2024-11-07T12:39:44.356045Z","iopub.status.idle":"2024-11-07T12:39:44.375661Z","shell.execute_reply.started":"2024-11-07T12:39:44.356012Z","shell.execute_reply":"2024-11-07T12:39:44.374773Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Dosyaların boyutlarını aynı hale getirelim.\n\nIMAGE_FOLDER_PATH = \"../working/train\"\nFILE_NAMES = os.listdir(IMAGE_FOLDER_PATH)\nWIDTH = 128\nHEIGHT = 128\n\n# Dosyaların yüklendiğini anlamak için bir çıktı ekleyelim.\n\nprint(f\"Toplam {len(FILE_NAMES)} dosya bulundu.\")\nprint(f\"İlk 5 dosya: {FILE_NAMES[:5]}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:44.376655Z","iopub.execute_input":"2024-11-07T12:39:44.376922Z","iopub.status.idle":"2024-11-07T12:39:44.400422Z","shell.execute_reply.started":"2024-11-07T12:39:44.376892Z","shell.execute_reply":"2024-11-07T12:39:44.399383Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Target stunu açarak kedi / köpek ayrımını yazdıralım.\n\ntargets=list()\nfull_paths=list()\nfor file_name in FILE_NAMES:\n    target=file_name.split(\".\")[0]\n    full_path=os.path.join(IMAGE_FOLDER_PATH, file_name)\n    full_paths.append(full_path)\n    targets.append(target)\n\ndataset=pd.DataFrame()\ndataset['image_path']=full_paths\ndataset['target']=targets\ndataset.head(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:44.401842Z","iopub.execute_input":"2024-11-07T12:39:44.402229Z","iopub.status.idle":"2024-11-07T12:39:44.499767Z","shell.execute_reply.started":"2024-11-07T12:39:44.402176Z","shell.execute_reply":"2024-11-07T12:39:44.498494Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Target'lardan gelen sonuçlarla kaçar adet kedi, köpek var diye bakalım. \n\ntarget_counts=dataset['target'].value_counts()\nprint(\"Köpek olarak işaretlenmiş dataların sayısı:{}\".format(target_counts['dog']))\nprint(\"Kedi olarak işaretlenmiş dataların sayısı::{}\".format(target_counts['cat']))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:44.500899Z","iopub.execute_input":"2024-11-07T12:39:44.501843Z","iopub.status.idle":"2024-11-07T12:39:44.518810Z","shell.execute_reply.started":"2024-11-07T12:39:44.501807Z","shell.execute_reply":"2024-11-07T12:39:44.517866Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# İlk kedi ve köpek görüntüsünü bulalım.\n\ncat_image_path = dataset[dataset['target'] == 'cat'].iloc[0]['image_path']\ndog_image_path = dataset[dataset['target'] == 'dog'].iloc[0]['image_path']\n\n# Kedi görüntüsünü gösterelim.\n\nplt.figure(figsize=(10,5))\n\nplt.subplot(1, 2, 1)\ncat_image = mpimg.imread(cat_image_path)\nplt.imshow(cat_image)\nplt.title('Cat')\n\n# Köpek görüntüsünü gösterelim.\n\nplt.subplot(1, 2, 2)\ndog_image = mpimg.imread(dog_image_path)\nplt.imshow(dog_image)\nplt.title('Dog')\n\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:44.519926Z","iopub.execute_input":"2024-11-07T12:39:44.520224Z","iopub.status.idle":"2024-11-07T12:39:45.174981Z","shell.execute_reply.started":"2024-11-07T12:39:44.520192Z","shell.execute_reply":"2024-11-07T12:39:45.174117Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# ImageDataGenerator ile veri artırma işlemleri ve resim boyutlarını ayarlayalım.\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,            # Tüm pikselleri 0-1 aralığına çekiyoruz\n    rotation_range=20,       # Görüntüyü rastgele 40 derece döndürme\n    width_shift_range=0.2,     # Görüntüyü yatayda %20 oranında kaydırma\n    height_shift_range=0.2,    # Görüntüyü dikeyde %20 oranında kaydırma\n    shear_range=0.2,           # Şeffaflık\n    zoom_range=0.2,            # Yakınlaştırma\n    horizontal_flip=False,      # Yatay çevirme\n    fill_mode='nearest'        # Yeni pikselleri doldurma\n)\n\n# Test/Doğrulama seti için yalnızca yeniden ölçekleme yalım. \ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# Eğitim verisini hazırlayalım: Verileri 128x128 boyutuna getir ve batch halinde alalım.\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=dataset,\n    directory=None,\n    x_col='image_path',\n    y_col='target',\n    target_size=(128, 128),\n    batch_size=32,\n    class_mode='binary'  # İkili sınıflandırma için 'binary'\n)\n\n# Test/Doğrulama verisini hazırlayalım.\nvalidation_generator = test_datagen.flow_from_dataframe(\n    dataframe=dataset,\n    directory=None,\n    x_col='image_path',\n    y_col='target',\n    target_size=(128, 128),\n    batch_size=32,\n    class_mode='binary'\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:45.176134Z","iopub.execute_input":"2024-11-07T12:39:45.176472Z","iopub.status.idle":"2024-11-07T12:39:45.736994Z","shell.execute_reply.started":"2024-11-07T12:39:45.176438Z","shell.execute_reply":"2024-11-07T12:39:45.736227Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Image Augmentation, görüntüleri çeşitli yöntemlerle zenginleştirme genel kavramını ifade ederken, Image Data Generator, bu kavramı uygulamak için kullanılabilecek bir araçtır. Bu nedendle Image Augmentation yerine  Image Data Generator kullanışmıştır. Görüntü artırma işlemlerini otomatikleştirme ve model eğitimine entegre etme açısından büyük kolaylık sağladığı için.","metadata":{}},{"cell_type":"code","source":"# Kedi ve köpek sayısını sayalım.\nlabel_counts = dataset['target'].value_counts()\n\n# Grafiği oluşturalım.\nplt.figure(figsize=(4, 3))\nlabel_counts.plot(kind='bar', color=['yellow', 'green'])\nplt.title('Cat and Dog Count')\nplt.xlabel('Class')\nplt.ylabel('Count')\nplt.xticks(rotation=0)\nplt.grid(axis='y')\n\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:45.740504Z","iopub.execute_input":"2024-11-07T12:39:45.740826Z","iopub.status.idle":"2024-11-07T12:39:45.919404Z","shell.execute_reply.started":"2024-11-07T12:39:45.740792Z","shell.execute_reply":"2024-11-07T12:39:45.918462Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Örnek bir kedi görüntüsü seçelim\ncat_image_path = dataset[dataset['target'] == 'cat'].sample(1)['image_path'].values[0]\n\n# Görüntüyü yükleyelim\ncat_image = cv2.imread(cat_image_path)\ncat_image = cv2.cvtColor(cat_image, cv2.COLOR_BGR2RGB)  # OpenCV BGR formatında yüklediği için RGB'ye çevirelim\n\n# RGB kanallarını ayıralım\nR, G, B = cat_image.copy(), cat_image.copy(), cat_image.copy()\n\n# Kırmızı kanal için sadece kırmızı bileşeni bırakalım.\nR[:, :, 1] = 0  # Yeşil kanal sıfırla\nR[:, :, 2] = 0  # Mavi kanal sıfırla\n\n# Yeşil kanal için sadece yeşil bileşeni bırakalım.\nG[:, :, 0] = 0  # Kırmızı kanal sıfırla\nG[:, :, 2] = 0  # Mavi kanal sıfırla\n\n# Mavi kanal için sadece mavi bileşeni bırakalım.\nB[:, :, 0] = 0  # Kırmızı kanal sıfırla\nB[:, :, 1] = 0  # Yeşil kanal sıfırla\n\n# Görüntüleri gösterelim\nplt.figure(figsize=(12, 6))\n\nplt.subplot(1, 4, 1)\nplt.imshow(cat_image)\nplt.title(\"Orijinal Görüntü\")\nplt.axis('off')\n\nplt.subplot(1, 4, 2)\nplt.imshow(R)\nplt.title(\"Kırmızı Kanal\")\nplt.axis('off')\n\nplt.subplot(1, 4, 3)\nplt.imshow(G)\nplt.title(\"Yeşil Kanal\")\nplt.axis('off')\n\nplt.subplot(1, 4, 4)\nplt.imshow(B)\nplt.title(\"Mavi Kanal\")\nplt.axis('off')\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:45.920745Z","iopub.execute_input":"2024-11-07T12:39:45.921723Z","iopub.status.idle":"2024-11-07T12:39:46.624581Z","shell.execute_reply.started":"2024-11-07T12:39:45.921676Z","shell.execute_reply":"2024-11-07T12:39:46.623715Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Genişlik ve yükseklik değerlerini saklayacak listeler oluşturalım,\nwidths = []\nheights = []\n\n# Her bir görüntünün boyutlarını hesaplayıp listeye ekleyelim\nfor img_path in dataset['image_path']:\n    with Image.open(img_path) as img:\n        width, height = img.size\n        widths.append(width)\n        heights.append(height)\n\n# Ortalamaları hesaplayalım.\navg_width = np.mean(widths)\navg_height = np.mean(heights)\n\nprint(f\"Görüntülerin ortalama genişliği: {avg_width:.2f} piksel\")\nprint(f\"Görüntülerin ortalama yüksekliği: {avg_height:.2f} piksel\") ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:46.625941Z","iopub.execute_input":"2024-11-07T12:39:46.626343Z","iopub.status.idle":"2024-11-07T12:39:49.971708Z","shell.execute_reply.started":"2024-11-07T12:39:46.626284Z","shell.execute_reply":"2024-11-07T12:39:49.970710Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\nimport os\n\n# Tüm görüntüleri kaydedeceğimiz yeni klasörü oluşturalım\nresized_dir = \"resized_images\"\nos.makedirs(resized_dir, exist_ok=True)\n\n# Tüm görselleri yeniden boyutlandıralım\nfor img_path in dataset['image_path']:\n    # Görseli aç ve yeniden boyutlandır\n    with Image.open(img_path) as img:\n        resized_img = img.resize((128, 128))\n        \n        # Yeni dosya yolunu belirleyelim\n        img_filename = os.path.basename(img_path) \n        resized_img_path = os.path.join(resized_dir, img_filename)\n        \n        # Yeniden boyutlandırılmış görüntüyü kaydedelim\n        resized_img.save(resized_img_path)\n\nprint(\"Tüm görüntüler başarıyla 128x128 piksel boyutuna getirildi ve 'resized_images' klasörüne kaydedildi.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:39:49.973001Z","iopub.execute_input":"2024-11-07T12:39:49.973422Z","iopub.status.idle":"2024-11-07T12:41:02.906749Z","shell.execute_reply.started":"2024-11-07T12:39:49.973374Z","shell.execute_reply":"2024-11-07T12:41:02.905777Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = next(train_generator)\n\n# İlk 5 görüntüyü görselleştirelim\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(10, 10))\nfor i in range(5):\n    plt.subplot(1, 5, i + 1)\n    plt.imshow(images[i])\n    plt.title(f\"Label: {int(labels[i])}\")\n    plt.axis('off')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:02.908063Z","iopub.execute_input":"2024-11-07T12:41:02.908770Z","iopub.status.idle":"2024-11-07T12:41:03.461451Z","shell.execute_reply.started":"2024-11-07T12:41:02.908722Z","shell.execute_reply":"2024-11-07T12:41:03.460362Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Veriyi %80 eğitim ve %20 test olarak ayıralım\ntrain_df, test_df = train_test_split(dataset, test_size=0.2, random_state=42)\n\nprint(f\"Eğitim verisi boyutu: {len(train_df)}\")\nprint(f\"Test verisi boyutu: {len(test_df)}\")\n\n# ImageDataGenerator ile normalizasyon işlemi yapalım\ndatagen = ImageDataGenerator(rescale=1./255)\n\n# Eğitim verisi generator'ünü uygulayalım.\ntrain_generator = datagen.flow_from_dataframe(\n    dataframe=train_df,\n    x_col='image_path',\n    y_col='target',\n    target_size=(128, 128),\n    batch_size=32,\n    class_mode='binary'\n)\n\n# Test verisi generator'ünü uygulayalım.\ntest_generator = datagen.flow_from_dataframe(\n    dataframe=test_df,\n    x_col='image_path',\n    y_col='target',\n    target_size=(128, 128),\n    batch_size=32,\n    class_mode='binary'\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:03.462495Z","iopub.execute_input":"2024-11-07T12:41:03.462776Z","iopub.status.idle":"2024-11-07T12:41:03.758530Z","shell.execute_reply.started":"2024-11-07T12:41:03.462745Z","shell.execute_reply":"2024-11-07T12:41:03.757800Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# İlk birkaç satırı görüntüleyelim\nprint(dataset.head())\n\n# Sütun adlarını kontrol edelim\nprint(dataset.columns)\n\n# Benzersiz görüntü yollarını kontrol edelim\nprint(dataset['image_path'].unique())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:03.759632Z","iopub.execute_input":"2024-11-07T12:41:03.759948Z","iopub.status.idle":"2024-11-07T12:41:03.772863Z","shell.execute_reply.started":"2024-11-07T12:41:03.759914Z","shell.execute_reply":"2024-11-07T12:41:03.771951Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n# Her görüntü yolunun varlığını kontrol edelim, yoksa bir çıktı olarak bize bir çıktı vermesini sağlayalım.\nfor path in dataset['image_path']:\n    if not os.path.exists(path):\n        print(f\"Görüntü yolu bulunamadı: {path}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:03.774176Z","iopub.execute_input":"2024-11-07T12:41:03.774664Z","iopub.status.idle":"2024-11-07T12:41:03.892713Z","shell.execute_reply.started":"2024-11-07T12:41:03.774618Z","shell.execute_reply":"2024-11-07T12:41:03.891860Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# CNN Modeli Oluşturalım\nmodel = models.Sequential()\n\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(layers.Conv2D(256, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dropout(0.5))  # Aşırı uyumu önlemek için dropout\nmodel.add(layers.Dense(1, activation='sigmoid'))  # İkili sınıflandırma için sigmoid\n\n# Modeli derleyelim,\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.RMSprop(learning_rate=1e-4),\n              metrics=['accuracy'])\n\n# Modelin özetini görüntüleyelim.\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:03.893973Z","iopub.execute_input":"2024-11-07T12:41:03.894347Z","iopub.status.idle":"2024-11-07T12:41:04.733698Z","shell.execute_reply.started":"2024-11-07T12:41:03.894298Z","shell.execute_reply":"2024-11-07T12:41:04.732790Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Test generator'ünü uygulayalım.\ntest_generator = datagen.flow_from_dataframe(\n    dataframe=test_df,\n    x_col='image_path',\n    y_col='target',\n    target_size=(128, 128),\n    batch_size=32,\n    class_mode='binary'\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:04.735100Z","iopub.execute_input":"2024-11-07T12:41:04.735556Z","iopub.status.idle":"2024-11-07T12:41:04.803667Z","shell.execute_reply.started":"2024-11-07T12:41:04.735503Z","shell.execute_reply":"2024-11-07T12:41:04.802985Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# train ve test işlemleri için kaç adımda işlem yapacağını belirleyelim.\nsteps_per_epoch = len(train_generator)\nvalidation_steps = len(test_generator)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:04.804754Z","iopub.execute_input":"2024-11-07T12:41:04.805058Z","iopub.status.idle":"2024-11-07T12:41:04.809387Z","shell.execute_reply.started":"2024-11-07T12:41:04.805024Z","shell.execute_reply":"2024-11-07T12:41:04.808361Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ilk bir kaç satırını yazdıralım.\nprint(train_df.head())\nprint(test_df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:04.810520Z","iopub.execute_input":"2024-11-07T12:41:04.810900Z","iopub.status.idle":"2024-11-07T12:41:04.822711Z","shell.execute_reply.started":"2024-11-07T12:41:04.810858Z","shell.execute_reply":"2024-11-07T12:41:04.821783Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#model parametrelieni belirleyelim.\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.RMSprop(learning_rate=1e-4),\n              metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:04.824116Z","iopub.execute_input":"2024-11-07T12:41:04.824474Z","iopub.status.idle":"2024-11-07T12:41:04.835864Z","shell.execute_reply.started":"2024-11-07T12:41:04.824442Z","shell.execute_reply":"2024-11-07T12:41:04.835089Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Test generatö'ünü uygulayalım yeniden.\ntest_generator = datagen.flow_from_dataframe(\n    dataframe=test_df,\n    x_col='image_path',\n    y_col='target',\n    target_size=(128, 128),\n    batch_size=32,\n    class_mode='binary'  # 'categorical' kullanmadığına emin ol\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:04.836842Z","iopub.execute_input":"2024-11-07T12:41:04.837182Z","iopub.status.idle":"2024-11-07T12:41:04.901120Z","shell.execute_reply.started":"2024-11-07T12:41:04.837150Z","shell.execute_reply":"2024-11-07T12:41:04.900456Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Bir örnek görüp verilerin doğruluğunu teyit edelim.\nimages, labels = next(test_generator)\nprint(images.shape, labels.shape)  # Görüntü ve etiket boyutunu kontrol et\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:04.902008Z","iopub.execute_input":"2024-11-07T12:41:04.902286Z","iopub.status.idle":"2024-11-07T12:41:04.952929Z","shell.execute_reply.started":"2024-11-07T12:41:04.902249Z","shell.execute_reply":"2024-11-07T12:41:04.952110Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Validation_steps ayarlayalım.\nvalidation_steps = len(test_df) // 32  # batch_size 32\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.RMSprop(learning_rate=1e-4),\n              metrics=['accuracy'])\n\nsteps_per_epoch = len(train_df) // 32  # batch_size 32","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:04.953879Z","iopub.execute_input":"2024-11-07T12:41:04.954162Z","iopub.status.idle":"2024-11-07T12:41:04.963322Z","shell.execute_reply.started":"2024-11-07T12:41:04.954131Z","shell.execute_reply":"2024-11-07T12:41:04.962384Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Modeli uygulayalım\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=steps_per_epoch,\n    validation_data=test_generator,\n    validation_steps=validation_steps,\n    epochs=10\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:41:04.964495Z","iopub.execute_input":"2024-11-07T12:41:04.964797Z","iopub.status.idle":"2024-11-07T12:43:53.861712Z","shell.execute_reply.started":"2024-11-07T12:41:04.964766Z","shell.execute_reply":"2024-11-07T12:43:53.860894Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Eğitim tarihini alalım\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\n# Doğruluk grafiğini çizdirelim\nplt.plot(epochs, acc, 'b', label='Eğitim Doğruluğu')\nplt.plot(epochs, val_acc, 'r', label='Doğrulama Doğruluğu')\nplt.title('Eğitim ve Doğrulama Doğruluğu')\nplt.legend()\nplt.figure()\n\n# Kayıp grafiğini çizdirelim,\nplt.plot(epochs, loss, 'b', label='Eğitim Kaybı')\nplt.plot(epochs, val_loss, 'r', label='Doğrulama Kaybı')\nplt.title('Eğitim ve Doğrulama Kaybı')\nplt.legend()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:43:53.862917Z","iopub.execute_input":"2024-11-07T12:43:53.863228Z","iopub.status.idle":"2024-11-07T12:43:54.443353Z","shell.execute_reply.started":"2024-11-07T12:43:53.863195Z","shell.execute_reply":"2024-11-07T12:43:54.442468Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Test veri kümesindeki performansını değerlendirelim\ntest_loss, test_acc = model.evaluate(test_generator)\nprint(f'Test Doğruluğu: {test_acc}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:43:54.449110Z","iopub.execute_input":"2024-11-07T12:43:54.449424Z","iopub.status.idle":"2024-11-07T12:44:00.951979Z","shell.execute_reply.started":"2024-11-07T12:43:54.449391Z","shell.execute_reply":"2024-11-07T12:44:00.951108Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Test veri setindeki tahminleri alalım,\ntest_generator.reset()  # Test verisini sıfırla\npredictions = model.predict(test_generator)\npredicted_classes = np.where(predictions > 0.5, 1, 0)  # 0.5 eşik değeri kullanarak sınıflandır\n\n# Gerçek etiketleri alalım,\ntrue_classes = test_generator.classes\nclass_labels = list(test_generator.class_indices.keys())  # Sınıf etiketleri\n\n# Yanlış sınıflandırılanları bulalım,\nincorrect_indices = np.where(predicted_classes.flatten() != true_classes)[0]\n\n# Yanlış sınıflandırmaları görüntüleyelim,\nplt.figure(figsize=(12, 12))\nfor i, incorrect_index in enumerate(incorrect_indices[:9]):  # İlk 9 yanlış sınıflandırmayı göster\n    plt.subplot(3, 3, i + 1)\n    img_path = test_generator.filepaths[incorrect_index]\n    img = plt.imread(img_path)\n    plt.imshow(img)\n    plt.title(f\"Gerçek: {class_labels[true_classes[incorrect_index]]}, Tahmin: {class_labels[predicted_classes[incorrect_index][0]]}\")\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()\n\n# Sınıflandırma raporunu görelim.\nprint(classification_report(true_classes, predicted_classes, target_names=class_labels))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:44:00.953106Z","iopub.execute_input":"2024-11-07T12:44:00.953457Z","iopub.status.idle":"2024-11-07T12:44:09.585786Z","shell.execute_reply.started":"2024-11-07T12:44:00.953421Z","shell.execute_reply":"2024-11-07T12:44:09.584832Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# YENİ BİR YAKLAŞIM...  ","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\n\n# Dosya dizini yeniden alalım.\ntrain_dir = '/kaggle/working/train'\n\n# Dosyaları listeleyelim\nfilenames = os.listdir(train_dir)\n\n# Kategorileri belirleyelim\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\n# DataFrame oluşturalım\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})\n\n# İlk 5 satırı görüntüleyelim.\nprint(df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:44:09.587161Z","iopub.execute_input":"2024-11-07T12:44:09.587956Z","iopub.status.idle":"2024-11-07T12:44:09.640373Z","shell.execute_reply.started":"2024-11-07T12:44:09.587908Z","shell.execute_reply":"2024-11-07T12:44:09.639576Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Modelde kullanılacak optimizasyon algoritmasınının parametrelerini tanımlayalım,\noptimizer=optimizers.SGD(learning_rate=1e-4, momentum=0.9)\nprint('tamamlandı')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:44:09.641384Z","iopub.execute_input":"2024-11-07T12:44:09.641669Z","iopub.status.idle":"2024-11-07T12:44:09.650016Z","shell.execute_reply.started":"2024-11-07T12:44:09.641638Z","shell.execute_reply":"2024-11-07T12:44:09.649141Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, GlobalMaxPooling2D\nfrom tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras import optimizers\n\n\nimage_size = 128 \ninput_shape = (image_size, image_size, 3)\n\n# VGG16 modelini yükle, ilk 15 katmanı donduralım\npre_trained_model = VGG16(input_shape=input_shape, include_top=False, weights=\"imagenet\")\n\nepochs = 5\nbatch_size = 64\n\nfor layer in pre_trained_model.layers[:15]:\n    layer.trainable = False\n\nfor layer in pre_trained_model.layers[15:]:\n    layer.trainable = True\n\n# Model katmanlarını belirleyelim\nlast_layer = pre_trained_model.get_layer('block5_pool')\nlast_output = last_layer.output\n\n# Flatten, Dense ve Dropout katmanları ekleyelim\nx = GlobalMaxPooling2D()(last_output)\nx = Dense(512, activation='relu')(x)\nx = Dropout(0.5)(x)\nx = layers.Dense(1, activation='sigmoid')(x)\n\n# Modeli oluşturtur\nmodel = Model(pre_trained_model.input, x)\n\n# Modeli derleyelim\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.SGD(learning_rate=1e-4, momentum=0.9),\n              metrics=['accuracy'])\n\n# Model özetini gösterelim\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:44:09.651249Z","iopub.execute_input":"2024-11-07T12:44:09.651602Z","iopub.status.idle":"2024-11-07T12:44:10.342486Z","shell.execute_reply.started":"2024-11-07T12:44:09.651566Z","shell.execute_reply":"2024-11-07T12:44:10.341553Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\n# Eğitim ve doğrulama setlerine bölelim\ntrain_df, validate_df = train_test_split(df, test_size=0.1, random_state=42)\n\n# Index'leri sıfırlayalım\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df = validate_df.reset_index(drop=True)\n\n# (Opsiyonel) Kodun hızlı test edilmesi için küçük bir örnek seti kullanabilirsin\n# validate_df = validate_df.sample(n=100).reset_index(drop=True)  # Doğrulama seti için küçük bir örnek\n# train_df = train_df.sample(n=1800).reset_index(drop=True)        # Eğitim seti için küçük bir örnek\n\n# Eğitim ve doğrulama veri setlerinin boyutlarını belirleyelim\ntotal_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\n\nprint(\"Toplam eğitim örneği sayısı:\", total_train)\nprint(\"Toplam doğrulama örneği sayısı:\", total_validate)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:44:10.343753Z","iopub.execute_input":"2024-11-07T12:44:10.344032Z","iopub.status.idle":"2024-11-07T12:44:10.356366Z","shell.execute_reply.started":"2024-11-07T12:44:10.344000Z","shell.execute_reply":"2024-11-07T12:44:10.355408Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Kategori sütununu string tipine çevirelim\ntrain_df['category'] = train_df['category'].astype(str)\nvalidate_df['category'] = validate_df['category'].astype(str)\n\nvalidate_datagen = ImageDataGenerator(rescale=1./255) \n\n# Eğitim seti için veri akışını sağlayalım\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory='/kaggle/working/resized_images',  # Resized görüntülerin bulunduğu dizin\n    x_col='filename',  # DataFrame'deki dosya adları\n    y_col='category',  # DataFrame'deki etiketler\n    target_size=(128, 128),  # Hedef boyut\n    batch_size=64,    # Batch boyutu\n    class_mode='binary',      # Sınıflandırma modu (binary)\n    shuffle=True,             # Karıştırma\n    seed=42                  # Tekrar üretilebilirlik için\n)\n\n# Doğrulama seti için veri akışını sağlayalım\nvalidate_generator = validate_datagen.flow_from_dataframe(\n    dataframe=validate_df,\n    directory='/kaggle/working/resized_images',  # Resized görüntülerin bulunduğu dizin\n    x_col='filename',\n    y_col='category',\n    target_size=(128, 128),\n    batch_size=64,\n    class_mode='binary',\n    shuffle=False  # Doğrulama setinde karıştırma yapılmaması için.\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:44:10.357684Z","iopub.execute_input":"2024-11-07T12:44:10.358354Z","iopub.status.idle":"2024-11-07T12:44:10.719122Z","shell.execute_reply.started":"2024-11-07T12:44:10.358291Z","shell.execute_reply":"2024-11-07T12:44:10.718132Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import keras_tuner as kt\nfrom tensorflow.keras import layers, models, optimizers\nfrom tensorflow.keras.callbacks import Callback\n\n# Her denemede epoch sonuçlarını yazdıran özel bir callback tanımlayalım.\nclass EpochResultCallback(Callback):\n    def on_epoch_end(self, epoch, logs=None):\n        logs = logs or {}\n        print(f\"Epoch {epoch + 1} - Loss: {logs.get('loss'):.4f} - Accuracy: {logs.get('accuracy'):.4f} - \"\n              f\"Val_Loss: {logs.get('val_loss'):.4f} - Val_Accuracy: {logs.get('val_accuracy'):.4f}\")\n\n# Modeli tanımlama fonksiyonu yazalım\ndef build_model(hp):\n    model = models.Sequential()\n    model.add(layers.Input(shape=(128, 128, 3)))\n\n    # VGG16'ya benzer yapıyı oluşturalım\n    model.add(layers.Conv2D(32, (3, 3), activation='relu'))\n    model.add(layers.MaxPooling2D((2, 2)))\n\n    model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n    model.add(layers.MaxPooling2D((2, 2)))\n\n    model.add(layers.Conv2D(128, (3, 3), activation='relu'))\n    model.add(layers.MaxPooling2D((2, 2)))\n\n    model.add(layers.Flatten())\n\n    # Dense layer ve dropout oranı için hiperparametre aralığı yazalım\n    dense_units = hp.Int('dense_units', min_value=128, max_value=512, step=64)\n    model.add(layers.Dense(dense_units, activation='relu'))\n    \n    dropout_rate = hp.Float('dropout_rate', min_value=0.2, max_value=0.5, step=0.1)\n    model.add(layers.Dropout(dropout_rate))\n    \n    # Çıktı katmanını belirleyelim\n    model.add(layers.Dense(1, activation='sigmoid'))\n\n    # Öğrenme oranı için hiperparametre aralığı belirleyelim\n    learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])\n    model.compile(optimizer=optimizers.Adam(learning_rate=learning_rate),\n                  loss='binary_crossentropy',\n                  metrics=['accuracy'])\n    \n    return model\n\n# Tuner yapılandırması yapalım\ntuner = kt.RandomSearch(\n    build_model,\n    objective='val_accuracy',\n    max_trials=5,  # Denenecek farklı hiperparametre kombinasyonlarının sayısı\n    executions_per_trial=1,  # Her kombinasyonu kaç kez çalıştıracağı\n    directory='my_dir',\n    project_name='cat_dog_hyperparameter_tuning'\n)\n\n# Eğitim ve doğrulama veri setlerini belirleyip Tuner'e her epoch sonrası yazdıracak callback ekleyelim\ntuner.search(\n    train_generator,\n    epochs=5,\n    validation_data=validation_generator,\n    callbacks=[EpochResultCallback()],  # Her epoch sonucu için callback\n    verbose=0  # Arka planda çalışan tüm epoch'ları callback üzerinden görmek için bu parametreyi sıfır yaptık\n)\n\n# Tüm denemeler tamamlandıktan sonra en iyi sonucu gösterelim\nbest_hps = tuner.get_best_hyperparameters(num_trials=1)[0]\nprint(f\"En iyi dense_units: {best_hps.get('dense_units')}\")\nprint(f\"En iyi dropout_rate: {best_hps.get('dropout_rate')}\")\nprint(f\"En iyi learning_rate: {best_hps.get('learning_rate')}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T12:44:10.720308Z","iopub.execute_input":"2024-11-07T12:44:10.720732Z","iopub.status.idle":"2024-11-07T13:34:20.607887Z","shell.execute_reply.started":"2024-11-07T12:44:10.720683Z","shell.execute_reply":"2024-11-07T13:34:20.606989Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Yenilenen modeli uygulayalım.\n\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n\nearly_stopping = EarlyStopping(\n    monitor='val_loss',  \n    patience=3,         \n    restore_best_weights=True  # En iyi ağırlıklara geri döner\n)\n\nhistory = model.fit(\n    train_generator,\n    epochs=20, \n    validation_data=validation_generator,\n    callbacks=[early_stopping],  \n    verbose=1\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T13:34:20.614229Z","iopub.execute_input":"2024-11-07T13:34:20.614546Z","iopub.status.idle":"2024-11-07T14:08:50.870188Z","shell.execute_reply.started":"2024-11-07T13:34:20.614515Z","shell.execute_reply":"2024-11-07T14:08:50.869383Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Eğitim ve doğrulama kaybını grafiğe dökelim,\nplt.figure(figsize=(14, 5))\n\n# Kayıp grafiğini çizelim,\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'], label='Eğitim Kaybı')\nplt.plot(history.history['val_loss'], label='Doğrulama Kaybı')\nplt.xlabel('Epoch')\nplt.ylabel('Kayıp')\nplt.title('Eğitim ve Doğrulama Kaybı')\nplt.legend()\n\n# Doğruluk grafiğini çizelim\nplt.subplot(1, 2, 2)\nplt.plot(history.history['accuracy'], label='Eğitim Doğruluğu')\nplt.plot(history.history['val_accuracy'], label='Doğrulama Doğruluğu')\nplt.xlabel('Epoch')\nplt.ylabel('Doğruluk')\nplt.title('Eğitim ve Doğrulama Doğruluğu')\nplt.legend()\n\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T14:08:50.871478Z","iopub.execute_input":"2024-11-07T14:08:50.871792Z","iopub.status.idle":"2024-11-07T14:08:51.331928Z","shell.execute_reply.started":"2024-11-07T14:08:50.871759Z","shell.execute_reply":"2024-11-07T14:08:51.331050Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Modelin doğrulama seti üzerindeki performansını değerlendirelim,\nval_loss, val_accuracy = model.evaluate(validate_generator, verbose=1)\nprint(f\"Doğrulama Kayıp (Loss): {val_loss}\")\nprint(f\"Doğrulama Doğruluğu (Accuracy): {val_accuracy}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T14:08:51.333134Z","iopub.execute_input":"2024-11-07T14:08:51.333558Z","iopub.status.idle":"2024-11-07T14:08:54.696404Z","shell.execute_reply.started":"2024-11-07T14:08:51.333511Z","shell.execute_reply":"2024-11-07T14:08:54.695504Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import classification_report, confusion_matrix\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Doğrulama seti üzerinde tahmin yapalım\nY_pred = model.predict(validate_generator, verbose=1)\ny_pred = np.round(Y_pred).astype(int).reshape(-1)  # 0 veya 1 olarak sınıflandırmak için yuvarlama\n\n# Gerçek etiketleri alalım\ny_true = validate_generator.classes\n\n# Karışıklık matrisi yapalım\nconf_matrix = confusion_matrix(y_true, y_pred)\nplt.figure(figsize=(8, 6))\nsns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')\nplt.xlabel('Tahmin Edilen')\nplt.ylabel('Gerçek')\nplt.title('Karışıklık Matrisi')\nplt.show()\n\n# Sınıflandırma raporu yazdıralım (doğruluk, hassasiyet, geri çağırma ve F1 skoru)\nprint(\"Sınıflandırma Raporu:\\n\")\nprint(classification_report(y_true, y_pred, target_names=validate_generator.class_indices.keys()))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T14:08:54.697615Z","iopub.execute_input":"2024-11-07T14:08:54.697907Z","iopub.status.idle":"2024-11-07T14:08:57.801642Z","shell.execute_reply.started":"2024-11-07T14:08:54.697876Z","shell.execute_reply":"2024-11-07T14:08:57.800673Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Modelin doğrulama setindeki tahminlerini alalım\nY_pred = model.predict(validate_generator, verbose=1)\ny_pred = np.round(Y_pred).astype(int).reshape(-1)  # 0 veya 1 olarak sınıflandırmak için yuvarlama\n\n# Gerçek etiketleri alalım\ny_true = validate_generator.classes\n\n# Yanlış sınıflandırılan örneklerin indekslerini bulalım\nincorrect_indices = np.where(y_pred != y_true)[0]\n\n# Yanlış sınıflandırılan 16 örneği görselleştirelim\nnum_wrong = 16\nfig, axes = plt.subplots(4, 4, figsize=(15, 15))\n\nfor i, ax in enumerate(axes.flat):\n    if i < num_wrong:\n        # Yanlış sınıflandırılan görsellerin dosya isimlerini alalım\n        img_path = validate_generator.filepaths[incorrect_indices[i]]\n        \n        # Görseli yükleyelim\n        img = plt.imread(img_path)\n        \n        # Görseli ax üzerinde çizdirelim\n        ax.imshow(img)\n        ax.axis('off')\n        \n        # Gerçek ve tahmin edilen etiketleri gösterelim\n        true_label = 'Dog' if y_true[incorrect_indices[i]] == 1 else 'Cat'\n        pred_label = 'Dog' if y_pred[incorrect_indices[i]] == 1 else 'Cat'\n        \n        ax.set_title(f\"True: {true_label}, Pred: {pred_label}\")\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-07T14:08:57.802894Z","iopub.execute_input":"2024-11-07T14:08:57.803488Z","iopub.status.idle":"2024-11-07T14:09:01.949730Z","shell.execute_reply.started":"2024-11-07T14:08:57.803450Z","shell.execute_reply":"2024-11-07T14:09:01.948709Z"}},"outputs":[],"execution_count":null}]}