{"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":"none","dataSources":[{"sourceId":120402,"databundleVersionId":14402712,"sourceType":"competition"}],"dockerImageVersionId":31259,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# *🐾 Cat vs Dog Image Classification | Deep Learning Project*","metadata":{}},{"cell_type":"markdown","source":"![](https://cdn-images-1.medium.com/max/800/1*XP4CMzNdFMp3UruACt1-Aw.png)","metadata":{}},{"cell_type":"markdown","source":"# *🐱🐶 Cat vs Dog Image Classification*\n\n**Competition:** [Kaggle Cat or Dog Image Classification Challenge](https://www.kaggle.com/competitions/cat-or-dog-image-classification-challenge/overview)\n\n**Objective:** Build a model to classify images as Cat (0) or Dog (1).\n\n**Steps in this Notebook:**\n1. Load and preprocess images\n2. Build CNN / Transfer Learning model\n3. Train the model (optional: pseudo-labeling)\n4. Predict on all dataset\n5. Generate `submission.csv`","metadata":{}},{"cell_type":"markdown","source":"## *İmport Libraries*","metadata":{}},{"cell_type":"code","source":"import os                  # Dosya ve dizin işlemleri için\nimport random              # Rastgele seçimler yapmak için\nimport warnings            # Uyarı mesajlarını yönetmek için\nwarnings.filterwarnings('ignore') # Tüm uyarı mesajlarını görmezden gelmek için filterwarnings ile 'ignore' ayarını yapıyoruz\n\nimport numpy as np         # Sayısal hesaplamalar ve matris işlemleri\nimport pandas as pd        # Veri analizi ve tablo işlemleri\nimport cv2                 # Görüntü işleme ve video/frame işlemleri\nimport kagglehub           # Kaggle veri setlerini kolayca çekmek için\n\nfrom sklearn.model_selection import train_test_split  # Veriyi eğitim/test setlerine ayırmak için\n\nfrom tensorflow.keras.models import Model            # Keras Functional API model tanımı\nfrom tensorflow.keras.layers import Flatten, Dense   # Katmanlar: Flatten ve tam bağlantılı Dense\nfrom tensorflow.keras.applications import VGG16      # Önceden eğitilmiş VGG16 modeli\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator  # Görüntü artırma ve ön işleme","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T12:42:56.898182Z","iopub.execute_input":"2026-02-12T12:42:56.898505Z","iopub.status.idle":"2026-02-12T12:43:19.877284Z","shell.execute_reply.started":"2026-02-12T12:42:56.898466Z","shell.execute_reply":"2026-02-12T12:43:19.876198Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## *İmport Data*","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\n\nDATASET_DIRECTORY = \"/kaggle/input/cat-or-dog-image-classification-challenge/data_mixed\"\n\nimg_path = []\nimg_name = []\n\nfor filename in os.listdir(DATASET_DIRECTORY):\n    if filename.lower().endswith(\".jpg\"):\n        img_path.append(os.path.join(DATASET_DIRECTORY, filename))\n        img_name.append(filename.split(\".\")[0])  # sadece sayı kısmı\n\ndf = pd.DataFrame({\n    \"img\": img_name,\n    \"filepath\": img_path\n})\n\ndf.head()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-02-12T12:43:19.879437Z","iopub.execute_input":"2026-02-12T12:43:19.880065Z","iopub.status.idle":"2026-02-12T12:43:19.992034Z","shell.execute_reply.started":"2026-02-12T12:43:19.880033Z","shell.execute_reply":"2026-02-12T12:43:19.991205Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## *CNN Model*","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions\n\n# --- Dataset ---\nDATASET_DIRECTORY = \"/kaggle/input/cat-or-dog-image-classification-challenge/data_mixed\"\n\nimg_path = []\nimg_name = []\n\nfor filename in os.listdir(DATASET_DIRECTORY):\n    if filename.lower().endswith(\".jpg\"):\n        img_path.append(os.path.join(DATASET_DIRECTORY, filename))\n        img_name.append(filename.split(\".\")[0])\n\ndf = pd.DataFrame({\n    \"img\": img_name,\n    \"filepath\": img_path\n})\n\n# --- ImageDataGenerator ---\nIMAGE_SIZE = 224  # ResNet50 için standart\nBATCH_SIZE = 32\n\ntest_gen = ImageDataGenerator(preprocessing_function=preprocess_input)\n\npredict_generator = test_gen.flow_from_dataframe(\n    df,\n    x_col=\"filepath\",\n    y_col=None,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    class_mode=None,\n    batch_size=BATCH_SIZE,\n    shuffle=False\n)\n\n# --- Pretrained Model ---\nmodel = ResNet50(weights='imagenet')\n\n# --- Batch Tahmin ---\npreds = model.predict(predict_generator, verbose=1)\n\n# --- Dog veya Cat olarak dönüştür ---\npreds_decoded = decode_predictions(preds, top=1)\nis_dog = [1 if 'dog' in pred[0][1].lower() else 0 for pred in preds_decoded]\n\n# --- Submission CSV ---\nsubmission = pd.DataFrame({\n    \"img\": df['img'],\n    \"is_dog\": is_dog\n})\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T12:43:34.978694Z","iopub.execute_input":"2026-02-12T12:43:34.979012Z","iopub.status.idle":"2026-02-12T12:55:20.687676Z","shell.execute_reply.started":"2026-02-12T12:43:34.978986Z","shell.execute_reply":"2026-02-12T12:55:20.686272Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv(\"submission.csv\", index=False)\nsubmission.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T12:55:20.689726Z","iopub.execute_input":"2026-02-12T12:55:20.690180Z","iopub.status.idle":"2026-02-12T12:55:20.716157Z","shell.execute_reply.started":"2026-02-12T12:55:20.690142Z","shell.execute_reply":"2026-02-12T12:55:20.715029Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## *Submission*","metadata":{}},{"cell_type":"code","source":"# Önceki submission'u yükle\nsubmission = pd.read_csv(\"submission.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T12:55:43.700430Z","iopub.execute_input":"2026-02-12T12:55:43.701593Z","iopub.status.idle":"2026-02-12T12:55:43.711668Z","shell.execute_reply.started":"2026-02-12T12:55:43.701554Z","shell.execute_reply":"2026-02-12T12:55:43.710624Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# DataFrame ile birleştir\ndf['label'] = submission['is_dog']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T12:56:10.706796Z","iopub.execute_input":"2026-02-12T12:56:10.707305Z","iopub.status.idle":"2026-02-12T12:56:10.713345Z","shell.execute_reply.started":"2026-02-12T12:56:10.707271Z","shell.execute_reply":"2026-02-12T12:56:10.711994Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission['is_dog'].value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T12:57:36.303471Z","iopub.execute_input":"2026-02-12T12:57:36.304035Z","iopub.status.idle":"2026-02-12T12:57:36.318603Z","shell.execute_reply.started":"2026-02-12T12:57:36.304002Z","shell.execute_reply":"2026-02-12T12:57:36.317603Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## *Dataset*","metadata":{}},{"cell_type":"code","source":"# label 0/1 yerine \"cat\"/\"dog\" olarak değiştir\ndf['label'] = df['label'].map({0: \"cat\", 1: \"dog\"})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T13:00:06.118824Z","iopub.execute_input":"2026-02-12T13:00:06.119335Z","iopub.status.idle":"2026-02-12T13:00:06.126184Z","shell.execute_reply.started":"2026-02-12T13:00:06.119301Z","shell.execute_reply":"2026-02-12T13:00:06.124911Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_df, val_df = train_test_split(df, test_size=0.2, stratify=df[\"label\"], random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T13:00:11.544719Z","iopub.execute_input":"2026-02-12T13:00:11.545778Z","iopub.status.idle":"2026-02-12T13:00:11.560512Z","shell.execute_reply.started":"2026-02-12T13:00:11.545742Z","shell.execute_reply":"2026-02-12T13:00:11.559454Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nIMAGE_SIZE = 128  # Küçük CNN için\nBATCH_SIZE = 32\n\n# Data Generator\ntrain_gen = ImageDataGenerator(rescale=1./255, horizontal_flip=True)\nval_gen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_gen.flow_from_dataframe(\n    train_df,\n    x_col=\"filepath\",\n    y_col=\"label\",\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    batch_size=BATCH_SIZE,\n    class_mode=\"binary\",\n    shuffle=True\n)\n\nval_generator = val_gen.flow_from_dataframe(\n    val_df,\n    x_col=\"filepath\",\n    y_col=\"label\",\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    batch_size=BATCH_SIZE,\n    class_mode=\"binary\",\n    shuffle=False\n)\n\n# Model\nmodel = Sequential([\n    Conv2D(32, (3,3), activation='relu', input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)),\n    MaxPooling2D(2,2),\n    Conv2D(64, (3,3), activation='relu'),\n    MaxPooling2D(2,2),\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dropout(0.3),\n    Dense(1, activation='sigmoid')\n])\n\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nmodel.fit(train_generator, validation_data=val_generator, epochs=10)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T13:00:28.814378Z","iopub.execute_input":"2026-02-12T13:00:28.815476Z","iopub.status.idle":"2026-02-12T13:15:55.446912Z","shell.execute_reply.started":"2026-02-12T13:00:28.815442Z","shell.execute_reply":"2026-02-12T13:15:55.445790Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## *Save Model*","metadata":{}},{"cell_type":"code","source":"# Keras formatında kaydet\nmodel.save(\"cat_dog_tl_model.keras\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T13:16:27.136849Z","iopub.execute_input":"2026-02-12T13:16:27.137249Z","iopub.status.idle":"2026-02-12T13:16:27.657580Z","shell.execute_reply.started":"2026-02-12T13:16:27.137219Z","shell.execute_reply":"2026-02-12T13:16:27.655869Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## *✅ Results & Submission*\n\n- The model predictions are saved in `submission.csv`.\n- You can submit this CSV to the Kaggle competition for evaluation.\n- Model can be saved for later reuse using Keras:\n\n```python\nmodel.save(\"cat_dog_model.h5\")","metadata":{}}]}