{"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":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"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","execution":{"iopub.status.busy":"2024-10-24T06:03:37.288542Z","iopub.execute_input":"2024-10-24T06:03:37.289606Z","iopub.status.idle":"2024-10-24T06:03:38.489101Z","shell.execute_reply.started":"2024-10-24T06:03:37.289557Z","shell.execute_reply":"2024-10-24T06:03:38.488018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\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\n\nimport glob\nimport os\nprint(\"Cats&Dogs Dataset Klasör içeriği:\",os.listdir(\"../input\"))","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:03:41.75646Z","iopub.execute_input":"2024-10-24T06:03:41.757231Z","iopub.status.idle":"2024-10-24T06:03:56.979145Z","shell.execute_reply.started":"2024-10-24T06:03:41.757171Z","shell.execute_reply":"2024-10-24T06:03:56.977675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\n\nzip_files = ['test1', 'train']\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":{"execution":{"iopub.status.busy":"2024-10-24T06:04:09.977154Z","iopub.execute_input":"2024-10-24T06:04:09.977863Z","iopub.status.idle":"2024-10-24T06:04:30.383706Z","shell.execute_reply.started":"2024-10-24T06:04:09.977817Z","shell.execute_reply":"2024-10-24T06:04:30.382368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n# Dosyaların boyutlarını aynı hale getirelim.\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 çıktı ekliyoruz\nprint(f\"Toplam {len(FILE_NAMES)} dosya bulundu.\")\nprint(f\"İlk 5 dosya: {FILE_NAMES[:5]}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:15:30.442691Z","iopub.execute_input":"2024-10-24T06:15:30.443149Z","iopub.status.idle":"2024-10-24T06:15:30.468331Z","shell.execute_reply.started":"2024-10-24T06:15:30.443109Z","shell.execute_reply":"2024-10-24T06:15:30.466904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"targets=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":{"execution":{"iopub.status.busy":"2024-10-24T06:09:59.554535Z","iopub.execute_input":"2024-10-24T06:09:59.555073Z","iopub.status.idle":"2024-10-24T06:09:59.640342Z","shell.execute_reply.started":"2024-10-24T06:09:59.555026Z","shell.execute_reply":"2024-10-24T06:09:59.639047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"target_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":{"execution":{"iopub.status.busy":"2024-10-24T06:10:14.271735Z","iopub.execute_input":"2024-10-24T06:10:14.2729Z","iopub.status.idle":"2024-10-24T06:10:14.288419Z","shell.execute_reply.started":"2024-10-24T06:10:14.272846Z","shell.execute_reply":"2024-10-24T06:10:14.28721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\n\n# WIDTH ve HEIGHT sabitlerini belirleyelim\nWIDTH, HEIGHT = 128, 128  # Örnek olarak 128x128 kullanıldı, kendi değerlerini ekleyebilirsin\n\n# get_side fonksiyonu: Görseller arasına boşluk koymak için\ndef get_side(img, side_type, side_size=250):\n    height, width, channel = img.shape\n    if side_type == \"horizontal\":\n        return np.ones((height, side_size, channel), dtype=np.float32) * 255\n    return np.ones((side_size, width, channel), dtype=np.float32) * 255\n\n# Galeri gösterme fonksiyonu\ndef show_gallery(show=\"both\"):\n    counter = 0\n    images = list()\n    vertical_images = []\n    \n    # Rastgele sıralama\n    rng_state = np.random.get_state()\n    np.random.shuffle(full_paths)\n    np.random.set_state(rng_state)\n    np.random.shuffle(targets)\n    \n    for path, target in zip(full_paths, targets):\n        if target != show and show != \"both\":\n            continue\n        counter += 1\n        if counter > 16:  # Toplamda 16 resim alacak şekilde sınırlandırıldı\n            break\n        \n        # Diskten resmi yükleme ve numpy array'e çevirme\n        img = load_img(path, target_size=(WIDTH, HEIGHT))\n        img = img_to_array(img)\n        \n        # Görsel arasına yatay boşluk ekleme\n        images.append(img)\n\n        if counter % 4 == 0:  # Her 4 resim için yatay birleştirme\n            himage = np.hstack((images))\n            vertical_images.append(himage)\n            images = list()\n\n    # Görselleri dikey olarak birleştirme\n    gallery = np.vstack((vertical_images)) \n    plt.figure(figsize=(10, 10))\n    plt.xticks([])\n    plt.yticks([])\n    \n    # Başlıklar\n    title = {\"both\": \"Dogs and Cats\", \"cat\": \"Cats\", \"dog\": \"Dogs\"}\n    plt.title(\"{} kategorisinden 16 örnek \".format(title[show]))\n    plt.imshow(gallery.astype(np.uint8))\n    plt.show()\n\n# Fonksiyon çağrıları\nshow_gallery(show=\"cat\")\nshow_gallery(show=\"dog\")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:14:01.073336Z","iopub.execute_input":"2024-10-24T06:14:01.073815Z","iopub.status.idle":"2024-10-24T06:14:02.47346Z","shell.execute_reply.started":"2024-10-24T06:14:01.073763Z","shell.execute_reply":"2024-10-24T06:14:02.471948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\n\n# WIDTH ve HEIGHT sabitleri\nWIDTH, HEIGHT = 128, 128  # Görsellerin boyutu\nCHANNELS = 3  # Renk kanalları (RGB)\n\n# Görsellerin boyutlarını analiz etme fonksiyonu\ndef analyze_images(image_paths):\n    total_images = len(image_paths)\n    widths = []\n    heights = []\n    channels = []\n    \n    mean_rgb = np.zeros(3)\n    var_rgb = np.zeros(3)\n    \n    for path in image_paths:\n        # Görüntüyü yükle ve numpy array'e çevir\n        img = load_img(path, target_size=(WIDTH, HEIGHT))\n        img_array = img_to_array(img)\n        \n        # Görüntü boyutlarını al\n        h, w, c = img_array.shape\n        heights.append(h)\n        widths.append(w)\n        channels.append(c)\n        \n        # Renk kanalları için ortalama ve varyans hesapla\n        mean_rgb += img_array.mean(axis=(0, 1))  # Her kanal için ortalamalar\n        var_rgb += img_array.var(axis=(0, 1))  # Her kanal için varyanslar\n    \n    # Ortalama değerleri toplam resim sayısına böl\n    mean_rgb /= total_images\n    var_rgb /= total_images\n    \n    # Görüntü boyutları ile ilgili istatistikleri yazdır\n    print(f\"Average Image Width: {np.mean(widths)}\")\n    print(f\"Average Image Height: {np.mean(heights)}\")\n    print(f\"Average Number of Channels: {np.mean(channels)}\")\n    \n    # Renk kanalları (RGB) için ortalama ve varyans değerlerini yazdır\n    print(f\"Mean RGB Values: {mean_rgb}\")\n    print(f\"Variance in RGB Values: {var_rgb}\")\n\n# Piksel dağılımını analiz etme ve histogram çizme fonksiyonu\ndef plot_pixel_distribution(image_paths):\n    all_pixels = np.zeros((len(image_paths) * WIDTH * HEIGHT, CHANNELS))\n    \n    for i, path in enumerate(image_paths):\n        # Görüntüyü yükle ve numpy array'e çevir\n        img = load_img(path, target_size=(WIDTH, HEIGHT))\n        img_array = img_to_array(img)\n        \n        # Piksel değerlerini kaydet\n        all_pixels[i * WIDTH * HEIGHT:(i + 1) * WIDTH * HEIGHT] = img_array.reshape(-1, CHANNELS)\n    \n    # Histogram çizimi\n    plt.figure(figsize=(12, 4))\n    colors = ['r', 'g', 'b']\n    for i, color in enumerate(colors):\n        plt.subplot(1, 3, i + 1)\n        plt.hist(all_pixels[:, i], bins=256, color=color, alpha=0.6)\n        plt.title(f'{color.upper()} Channel Distribution')\n        plt.xlabel('Pixel Value')\n        plt.ylabel('Frequency')\n    \n    plt.tight_layout()\n    plt.show()\n\n# Örnek çağrılar\nanalyze_images(full_paths[:16])  # İlk 16 görüntü için analiz\nplot_pixel_distribution(full_paths[:16])  # İlk 16 görüntü için piksel dağılımı analizi\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:16:06.297455Z","iopub.execute_input":"2024-10-24T06:16:06.297911Z","iopub.status.idle":"2024-10-24T06:16:08.401156Z","shell.execute_reply.started":"2024-10-24T06:16:06.297871Z","shell.execute_reply":"2024-10-24T06:16:08.399496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=models.Sequential()\nmodel.add(layers.Conv2D(32, (3,3), activation=\"relu\", input_shape=(WIDTH, HEIGHT, 3)))\nmodel.add(layers.Conv2D(32, (3,3), activation=\"relu\"))\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Dropout(0.25))\n\nmodel.add(layers.Conv2D(64, (3,3), activation=\"relu\"))\nmodel.add(layers.Conv2D(64, (3,3), activation=\"relu\"))\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Dropout(0.25))\n\nmodel.add(layers.Conv2D(128, (3,3), activation=\"relu\"))\nmodel.add(layers.Conv2D(128, (3,3), activation=\"relu\"))\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Dropout(0.25))\n\nmodel.add(layers.Conv2D(64, (3,3), activation=\"relu\"))\nmodel.add(layers.Conv2D(64, (3,3), activation=\"relu\"))\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Dropout(0.25))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512, activation=\"relu\"))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1, activation=\"sigmoid\"))\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:16:55.379237Z","iopub.execute_input":"2024-10-24T06:16:55.379685Z","iopub.status.idle":"2024-10-24T06:16:55.91829Z","shell.execute_reply.started":"2024-10-24T06:16:55.379642Z","shell.execute_reply":"2024-10-24T06:16:55.916811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\n\n# CNN modelini oluşturma\nmodel = Sequential()\n\n# İlk Conv2D ve MaxPooling katmanları\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(WIDTH, HEIGHT, 3)))\nmodel.add(MaxPooling2D((2, 2)))\n\n# İkinci Conv2D ve MaxPooling katmanları\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2)))\n\n# Üçüncü Conv2D ve MaxPooling katmanları\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2)))\n\n# Dropout katmanı ekleyerek overfitting'i önlemeye çalışıyoruz\nmodel.add(Dropout(0.5))\n\n# Fully connected (Dense) katmanlar\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))  # Dropout eklenmesi\n\n# Çıkış katmanı (Binary classification: cat or dog)\nmodel.add(Dense(1, activation='sigmoid'))\n\n# Modeli derleme\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n\n# Model özeti\nmodel.summary() ","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:23:14.930246Z","iopub.execute_input":"2024-10-24T06:23:14.930653Z","iopub.status.idle":"2024-10-24T06:23:15.103615Z","shell.execute_reply.started":"2024-10-24T06:23:14.930615Z","shell.execute_reply":"2024-10-24T06:23:15.102506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import load_img, img_to_array\n\ndef preprocess_images(image_paths):\n    images = []\n    for path in image_paths:\n        # Görüntüyü yükle ve yeniden boyutlandır\n        img = load_img(path, target_size=(WIDTH, HEIGHT))\n        # Görüntüyü numpy array'e çevir\n        img_array = img_to_array(img)\n        # Normalizasyon: Piksel değerlerini [0, 1] aralığına çekme\n        img_array /= 255.0\n        images.append(img_array)\n    \n    # Tüm görüntüleri bir numpy dizisine dönüştür\n    images_array = np.array(images)\n    \n    # Çıktı olarak görüntülerin sayısını ve boyutunu yazdır\n    print(f\"Görüntülerin Sayısı: {images_array.shape[0]}\")\n    print(f\"Görüntü Boyutu: {images_array.shape[1:]}\")  # (height, width, channels)\n    \n    return images_array\n\n# Ön işleme fonksiyonunu eğitim, doğrulama ve test setlerine uygulama\ntrain_images = preprocess_images(train_paths)\nval_images = preprocess_images(val_paths)\ntest_images = preprocess_images(test_paths)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:26:39.284744Z","iopub.execute_input":"2024-10-24T06:26:39.28539Z","iopub.status.idle":"2024-10-24T06:27:23.282083Z","shell.execute_reply.started":"2024-10-24T06:26:39.285335Z","shell.execute_reply":"2024-10-24T06:27:23.280201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\n\n# EarlyStopping callback'i oluşturma\nearly_stopping = EarlyStopping(\n    monitor='val_loss',  # İzlenecek metrik\n    patience=5,          # İyileşme olmadan kaç epoch bekleyeceği\n    restore_best_weights=True  # En iyi ağırlıkları geri yükle\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:29:14.164977Z","iopub.execute_input":"2024-10-24T06:29:14.165508Z","iopub.status.idle":"2024-10-24T06:29:14.17279Z","shell.execute_reply.started":"2024-10-24T06:29:14.165463Z","shell.execute_reply":"2024-10-24T06:29:14.171439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\n\n# Etiketleri 0 ve 1'e dönüştürme\ntrain_labels = np.array([1 if label == 'dog' else 0 for label in train_labels])\nval_labels = np.array([1 if label == 'dog' else 0 for label in val_labels])\n\n# Eğitim etiketlerini kontrol et\nprint(\"Train images shape:\", train_images.shape)\nprint(\"Train labels shape:\", train_labels.shape)\nprint(\"Unique labels in train labels:\", set(train_labels))","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:32:35.805456Z","iopub.execute_input":"2024-10-24T06:32:35.805992Z","iopub.status.idle":"2024-10-24T06:32:35.824313Z","shell.execute_reply.started":"2024-10-24T06:32:35.805908Z","shell.execute_reply":"2024-10-24T06:32:35.822919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Modeli eğitme\nhistory = model.fit(train_images, train_labels,\n                    validation_data=(val_images, val_labels),\n                    epochs=20,\n                    batch_size=32,\n                    callbacks=[early_stopping])","metadata":{"execution":{"iopub.status.busy":"2024-10-24T06:32:52.512058Z","iopub.execute_input":"2024-10-24T06:32:52.512516Z","iopub.status.idle":"2024-10-24T07:43:34.396613Z","shell.execute_reply.started":"2024-10-24T06:32:52.512476Z","shell.execute_reply":"2024-10-24T07:43:34.394988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Eğitim kaybı ve doğruluğunu çizme\ndef plot_training_history(history):\n    # Kaybı çiz\n    plt.figure(figsize=(12, 5))\n    \n    # Kaybı\n    plt.subplot(1, 2, 1)\n    plt.plot(history.history['loss'], label='Eğitim Kaybı')\n    plt.plot(history.history['val_loss'], label='Doğrulama Kaybı')\n    plt.title('Eğitim ve Doğrulama Kaybı')\n    plt.xlabel('Epoch')\n    plt.ylabel('Kaybı')\n    plt.legend()\n\n    # Doğruluğu\n    plt.subplot(1, 2, 2)\n    plt.plot(history.history['accuracy'], label='Eğitim Doğruluğu')\n    plt.plot(history.history['val_accuracy'], label='Doğrulama Doğruluğu')\n    plt.title('Eğitim ve Doğrulama Doğruluğu')\n    plt.xlabel('Epoch')\n    plt.ylabel('Doğruluk')\n    plt.legend()\n\n    plt.tight_layout()\n    plt.show()\n\n# Fonksiyonu çağır\nplot_training_history(history)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T07:44:50.744136Z","iopub.execute_input":"2024-10-24T07:44:50.744634Z","iopub.status.idle":"2024-10-24T07:44:51.427167Z","shell.execute_reply.started":"2024-10-24T07:44:50.744589Z","shell.execute_reply":"2024-10-24T07:44:51.425752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Test etiketlerini sayısal formata dönüştürme\ntest_labels_numeric = np.array([1 if label == 'dog' else 0 for label in test_labels])\n\n# Test etiketlerinin şeklini kontrol et\nprint(\"Test labels shape:\", test_labels_numeric.shape)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T07:48:03.870199Z","iopub.execute_input":"2024-10-24T07:48:03.870726Z","iopub.status.idle":"2024-10-24T07:48:03.879478Z","shell.execute_reply.started":"2024-10-24T07:48:03.870682Z","shell.execute_reply":"2024-10-24T07:48:03.878036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Test seti üzerinde modelin değerlendirilmesi\ntest_loss, test_accuracy = model.evaluate(test_images, test_labels_numeric)\nprint(f\"Test Kaybı: {test_loss:.4f}, Test Doğruluğu: {test_accuracy:.4f}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T07:48:33.660752Z","iopub.execute_input":"2024-10-24T07:48:33.661204Z","iopub.status.idle":"2024-10-24T07:49:00.015099Z","shell.execute_reply.started":"2024-10-24T07:48:33.661165Z","shell.execute_reply":"2024-10-24T07:49:00.013592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# İlk 3 test görüntüsü için tahmin yapma\npredictions = model.predict(test_images[:5])\npredicted_classes = ['dog' if pred > 0.5 else 'cat' for pred in predictions]\n\n# Görüntüleri ve tahminleri göster\nfor i in range(3):\n    plt.imshow(test_images[i])\n    plt.title(f'Tahmin: {predicted_classes[i]}')\n    plt.axis('off')\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T07:49:41.152391Z","iopub.execute_input":"2024-10-24T07:49:41.152848Z","iopub.status.idle":"2024-10-24T07:49:42.053709Z","shell.execute_reply.started":"2024-10-24T07:49:41.152783Z","shell.execute_reply":"2024-10-24T07:49:42.052377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, classification_report\n\n# Test seti üzerindeki tahminleri al\ntest_predictions = model.predict(test_images)\npredicted_classes = np.array([1 if pred > 0.5 else 0 for pred in test_predictions])\n\n# Karışıklık matrisini hesapla\ncm = confusion_matrix(test_labels_numeric, predicted_classes)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T07:51:53.427412Z","iopub.execute_input":"2024-10-24T07:51:53.427895Z","iopub.status.idle":"2024-10-24T07:52:16.289661Z","shell.execute_reply.started":"2024-10-24T07:51:53.427852Z","shell.execute_reply":"2024-10-24T07:52:16.288321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\n\n# Karışıklık matrisini görselleştir\nplt.figure(figsize=(8, 6))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Cat', 'Dog'], yticklabels=['Cat', 'Dog'])\nplt.xlabel('Tahmin Edilen Sınıf')\nplt.ylabel('Gerçek Sınıf')\nplt.title('Karışıklık Matrisi')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T07:53:08.527717Z","iopub.execute_input":"2024-10-24T07:53:08.52826Z","iopub.status.idle":"2024-10-24T07:53:09.239986Z","shell.execute_reply.started":"2024-10-24T07:53:08.528215Z","shell.execute_reply":"2024-10-24T07:53:09.238778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Yanlış sınıflandırılan örnekleri bul\nincorrect_indices = np.where(predicted_classes != test_labels_numeric)[0]\n\n# Yanlış sınıflandırılan örneklerin sayısı\nnum_incorrect = len(incorrect_indices)\n\n# Görselleştirmek istediğiniz örnek sayısını belirleyin\nnum_to_display = min(num_incorrect, 10)  # En fazla 10 örnek gösterelim\n\n# Görselleştirme\nplt.figure(figsize=(15, 8))\n\nfor i in range(num_to_display):\n    index = incorrect_indices[i]\n    plt.subplot(2, 5, i + 1)  # 2 satır, 5 sütun\n    plt.imshow(test_images[index])  # Test görüntüsünü göster\n    plt.title(f\"Gerçek: {'Dog' if test_labels_numeric[index] == 1 else 'Cat'}\\nTahmin: {'Dog' if predicted_classes[index] == 1 else 'Cat'}\")\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T07:54:24.763228Z","iopub.execute_input":"2024-10-24T07:54:24.764194Z","iopub.status.idle":"2024-10-24T07:54:26.426355Z","shell.execute_reply.started":"2024-10-24T07:54:24.76414Z","shell.execute_reply":"2024-10-24T07:54:26.424846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"birçok deneme yaptım en sonuncusu olarak bu karnel'i ürettim.","metadata":{}}]}