{"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":"gpu","dataSources":[{"sourceId":120402,"databundleVersionId":14402712,"sourceType":"competition"},{"sourceId":13664544,"sourceType":"datasetVersion","datasetId":8687890}],"dockerImageVersionId":31193,"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},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# I have downloaded the data localy then make the label by seeing the pic is it dog or not around 250 samples \n# You can use it if you dont wanna make the lables by own ","metadata":{}},{"cell_type":"code","source":"import pandas as pd\n\ndf = pd.read_csv('/kaggle/input/handmade-metadata/metaData.csv')\ndf","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-09T08:03:52.420028Z","iopub.execute_input":"2025-11-09T08:03:52.420443Z","iopub.status.idle":"2025-11-09T08:03:55.224691Z","shell.execute_reply.started":"2025-11-09T08:03:52.420417Z","shell.execute_reply":"2025-11-09T08:03:55.223530Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ============================================================\n# Cat or Dog Image Classification Challenge\n# Starter Notebook\n# ============================================================\n\nimport pandas as pd\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\n\n# ---------------------------\n# Load metadata\n# ---------------------------\nmeta_path = \"/kaggle/input/handmade-metadata/metaData.csv\"\ndf = pd.read_csv(meta_path)\n\nprint(\" Metadata loaded successfully!\")\nprint(df.head())\n\n# ---------------------------\n# Define image folder\n# ---------------------------\nimg_folder = \"/kaggle/input/cat-or-dog-image-classification-challenge/data_mixed\"\n\n# ---------------------------\n# Helper function to load image by ID\n# ---------------------------\ndef load_image(img_id):\n    img_path = os.path.join(img_folder, f\"{img_id}.jpg\")\n    img = cv2.imread(img_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    return img\n\n# ---------------------------\n# Example: Display few images\n# ---------------------------\nfig, axes = plt.subplots(2, 3, figsize=(10, 6))\nfor i, ax in enumerate(axes.flat):\n    img_id = df.loc[i, \"img\"]\n    label = df.loc[i, \"is_dog\"]\n    image = load_image(img_id)\n    ax.imshow(image)\n    ax.set_title(f\"ID: {img_id} | Label: {'Dog' if label == 1 else 'Cat'}\")\n    ax.axis(\"off\")\n\nplt.tight_layout()\nplt.show()\n\n# ---------------------------\n# Train-Test Split (Example)\n# ---------------------------\nfrom sklearn.model_selection import train_test_split\n\ntrain_df, val_df = train_test_split(df, test_size=0.2, stratify=df[\"is_dog\"], random_state=42)\nprint(f\"Train size: {len(train_df)}, Validation size: {len(val_df)}\")\n\n# ---------------------------\n# Ready for model training!\n# ---------------------------\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-09T08:10:04.702513Z","iopub.execute_input":"2025-11-09T08:10:04.702903Z","iopub.status.idle":"2025-11-09T08:10:07.113260Z","shell.execute_reply.started":"2025-11-09T08:10:04.702875Z","shell.execute_reply":"2025-11-09T08:10:07.111363Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"So the data is good to go then make the code ","metadata":{}},{"cell_type":"markdown","source":"# importing","metadata":{}},{"cell_type":"code","source":"!pip install --upgrade pip\n!pip install \"protobuf<4.24\" --force-reinstall\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-09T08:26:40.356558Z","iopub.execute_input":"2025-11-09T08:26:40.357205Z","iopub.status.idle":"2025-11-09T08:26:48.464060Z","shell.execute_reply.started":"2025-11-09T08:26:40.357182Z","shell.execute_reply":"2025-11-09T08:26:48.463053Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ============================================================\n# Cat or Dog Image Classification Challenge - Full Starter Code\n# With Data Augmentation\n# ============================================================\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport cv2\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import layers, models\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\n# ---------------------------\n# Load Metadata\n# ---------------------------\nmeta_path = \"/kaggle/input/handmade-metadata/metaData.csv\"\ndf = pd.read_csv(meta_path)\nprint(\" Metadata loaded successfully!\")\nprint(df.head())\n\n# ---------------------------\n# Base Image Folder\n# ---------------------------\nIMG_DIR = \"/kaggle/input/cat-or-dog-image-classification-challenge/data_mixed\"\n\n# ---------------------------\n# Image Size and Parameters\n# ---------------------------\nIMG_SIZE = (128, 128)\nBATCH_SIZE = 32\nEPOCHS = 50  # participants can increase this later\n\n# ---------------------------\n# Load Images into Arrays\n# ---------------------------\ndef load_image(img_id):\n    path = os.path.join(IMG_DIR, f\"{img_id}.jpg\")\n    img = cv2.imread(path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = cv2.resize(img, IMG_SIZE)\n    return img\n\n# Load all images and labels\nimages = np.array([load_image(i) for i in df[\"img\"]])\nlabels = np.array(df[\"is_dog\"])\n\nprint(f\"Loaded {len(images)} images successfully!\")\n\n# ---------------------------\n# Split Train and Validation\n# ---------------------------\nX_train, X_val, y_train, y_val = train_test_split(\n    images, labels, test_size=0.2, stratify=labels, random_state=42\n)\n\n# ---------------------------\n# Data Augmentation\n# ---------------------------\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\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\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_gen = train_datagen.flow(X_train, y_train, batch_size=BATCH_SIZE)\nval_gen = val_datagen.flow(X_val, y_val, batch_size=BATCH_SIZE)\n\n# ---------------------------\n# Build CNN Model\n# ---------------------------\nmodel = models.Sequential([\n    layers.Conv2D(32, (3,3), activation='relu', input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3)),\n    layers.MaxPooling2D(2,2),\n\n    layers.Conv2D(64, (3,3), activation='relu'),\n    layers.MaxPooling2D(2,2),\n\n    layers.Conv2D(128, (3,3), activation='relu'),\n    layers.MaxPooling2D(2,2),\n\n    layers.Flatten(),\n    layers.Dense(128, activation='relu'),\n    layers.Dropout(0.5),\n    layers.Dense(1, activation='sigmoid')\n])\n\nmodel.compile(\n    optimizer='adam',\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\nmodel.summary()\n\n# ---------------------------\n# Train Model\n# ---------------------------\nhistory = model.fit(\n    train_gen,\n    validation_data=val_gen,\n    epochs=EPOCHS,\n    verbose=1\n)\n\n# ---------------------------\n# Visualize Training\n# ---------------------------\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nplt.plot(history.history['accuracy'], label='Train Acc')\nplt.plot(history.history['val_accuracy'], label='Val Acc')\nplt.legend()\nplt.title('Accuracy')\n\nplt.subplot(1,2,2)\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\n# ---------------------------\n# Generate Predictions for Submission\n# ---------------------------\npreds = model.predict(val_gen, verbose=1).ravel()\npreds = np.clip(preds, 0, 1)\n\nsubmission = pd.DataFrame({\n    \"img\": df[\"img\"].iloc[y_val.index] if hasattr(y_val, \"index\") else np.arange(len(y_val)),\n    \"is_dog\": preds[:len(y_val)]\n})\n\nsubmission.to_csv(\"submission.csv\", index=False)\nprint(\"submission.csv created successfully!\")\nprint(submission.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-09T08:27:39.833778Z","iopub.execute_input":"2025-11-09T08:27:39.834163Z","iopub.status.idle":"2025-11-09T08:28:24.682983Z","shell.execute_reply.started":"2025-11-09T08:27:39.834131Z","shell.execute_reply":"2025-11-09T08:28:24.682071Z"}},"outputs":[],"execution_count":null}]}