{"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":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":5441,"databundleVersionId":38425}],"dockerImageVersionId":31287,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import zipfile\nimport os\n\nzip_path = \"/kaggle/input/competitions/dogs-vs-cats-redux-kernels-edition/train.zip\"\nextract_path = \"/kaggle/working/train\"\n\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_path)\n\nprint(\"Done extracting!\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-03-19T23:41:21.488279Z","iopub.execute_input":"2026-03-19T23:41:21.4885Z","iopub.status.idle":"2026-03-19T23:41:28.769876Z","shell.execute_reply.started":"2026-03-19T23:41:21.488479Z","shell.execute_reply":"2026-03-19T23:41:28.769275Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import shutil\n\nbase_dir = \"/kaggle/working/data\"\ncat_dir = os.path.join(base_dir, \"cat\")\ndog_dir = os.path.join(base_dir, \"dog\")\n\nos.makedirs(cat_dir, exist_ok=True)\nos.makedirs(dog_dir, exist_ok=True)\nprint(\"Done extracting!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-19T23:42:29.459833Z","iopub.execute_input":"2026-03-19T23:42:29.460171Z","iopub.status.idle":"2026-03-19T23:42:29.46565Z","shell.execute_reply.started":"2026-03-19T23:42:29.460135Z","shell.execute_reply":"2026-03-19T23:42:29.465042Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport shutil\n\nsource_dir = \"/kaggle/working/train/train\"\nbase_dir = \"/kaggle/working/data\"\n\ncat_dir = os.path.join(base_dir, \"cat\")\ndog_dir = os.path.join(base_dir, \"dog\")\n\n# حذف القديم لو موجود\nif os.path.exists(base_dir):\n    shutil.rmtree(base_dir)\n\nos.makedirs(cat_dir)\nos.makedirs(dog_dir)\n\ncount_cat = 0\ncount_dog = 0\n\nfor filename in os.listdir(source_dir):\n    if filename.endswith(\".jpg\"):\n        src = os.path.join(source_dir, filename)\n\n        if filename.startswith(\"cat\"):\n            shutil.copy(src, cat_dir)\n            count_cat += 1\n\n        elif filename.startswith(\"dog\"):\n            shutil.copy(src, dog_dir)\n            count_dog += 1\n\nprint(\"Cats:\", count_cat)\nprint(\"Dogs:\", count_dog)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-19T23:42:34.40331Z","iopub.execute_input":"2026-03-19T23:42:34.403602Z","iopub.status.idle":"2026-03-19T23:42:37.09683Z","shell.execute_reply.started":"2026-03-19T23:42:34.403579Z","shell.execute_reply":"2026-03-19T23:42:37.096076Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ==========================================\n# 1️⃣ IMPORT LIBRARIES\n# ==========================================\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport matplotlib.pyplot as plt\n\n# ==========================================\n# 2️⃣ LOAD DATA\n# ==========================================\n\ndata_dir = \"/kaggle/working/data\"\n\nimg_size = 150\nbatch_size = 32\n\ntrain_ds = tf.keras.preprocessing.image_dataset_from_directory(\n    data_dir,\n    validation_split=0.2,\n    subset=\"training\",\n    seed=42,\n    image_size=(img_size, img_size),\n    batch_size=batch_size\n)\n\nval_ds = tf.keras.preprocessing.image_dataset_from_directory(\n    data_dir,\n    validation_split=0.2,\n    subset=\"validation\",\n    seed=42,\n    image_size=(img_size, img_size),\n    batch_size=batch_size\n)\n\n# ==========================================\n# 3️⃣ PERFORMANCE OPTIMIZATION\n# ==========================================\n\nAUTOTUNE = tf.data.AUTOTUNE\n\ntrain_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)\nval_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)\n\n# ==========================================\n# 4️⃣ DATA AUGMENTATION (مهم جداً)\n# ==========================================\n\ndata_augmentation = keras.Sequential([\n    layers.RandomFlip(\"horizontal\"),\n    layers.RandomRotation(0.1),\n    layers.RandomZoom(0.1),\n])\n\n# ==========================================\n# 5️⃣ BUILD CNN MODEL\n# ==========================================\n\nmodel = keras.Sequential([\n    \n    # Augmentation + Normalization\n    data_augmentation,\n    layers.Rescaling(1./255),\n\n    # CNN Layers\n    layers.Conv2D(32, (3,3), activation='relu'),\n    layers.MaxPooling2D(),\n\n    layers.Conv2D(64, (3,3), activation='relu'),\n    layers.MaxPooling2D(),\n\n    layers.Conv2D(128, (3,3), activation='relu'),\n    layers.MaxPooling2D(),\n\n    # Dense Layers\n    layers.Flatten(),\n    layers.Dense(128, activation='relu'),\n    layers.Dropout(0.5),   # يقلل Overfitting\n    layers.Dense(1, activation='sigmoid')\n])\n\n# ==========================================\n# 6️⃣ COMPILE\n# ==========================================\n\nmodel.compile(\n    optimizer='adam',\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\nmodel.summary()\n\n# ==========================================\n# 7️⃣ EARLY STOPPING\n# ==========================================\n\nearly_stop = keras.callbacks.EarlyStopping(\n    monitor='val_loss',\n    patience=5,\n    restore_best_weights=True\n)\n\n# ==========================================\n# 8️⃣ TRAIN MODEL\n# ==========================================\n\nhistory = model.fit(\n    train_ds,\n    validation_data=val_ds,\n    epochs=20,\n    callbacks=[early_stop]\n)\n\n# ==========================================\n# 9️⃣ SAVE MODEL\n# ==========================================\n\nmodel.save(\"model.h5\", save_format=\"h5\")\n\nprint(\"✅ Model saved!\")\n\n# ==========================================\n# 🔟 PLOT RESULTS\n# ==========================================\n\nplt.figure(figsize=(12,5))\n\n# Accuracy\nplt.subplot(1,2,1)\nplt.plot(history.history['accuracy'], label='Train Acc')\nplt.plot(history.history['val_accuracy'], label='Val Acc')\nplt.title(\"Accuracy\")\nplt.legend()\n\n# Loss\nplt.subplot(1,2,2)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Val Loss')\nplt.title(\"Loss\")\nplt.legend()\n\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-19T23:42:41.864533Z","iopub.execute_input":"2026-03-19T23:42:41.865182Z","iopub.status.idle":"2026-03-19T23:49:08.9274Z","shell.execute_reply.started":"2026-03-19T23:42:41.86515Z","shell.execute_reply":"2026-03-19T23:49:08.926636Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import zipfile\n\nwith zipfile.ZipFile('/kaggle/working/model1.zip', 'w') as zipf:\n    zipf.write('/kaggle/working/model.keras', arcname='model.keras')\n\nprint(\"Done zipping!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-19T00:16:41.25031Z","iopub.execute_input":"2026-03-19T00:16:41.251016Z","iopub.status.idle":"2026-03-19T00:16:41.374208Z","shell.execute_reply.started":"2026-03-19T00:16:41.250984Z","shell.execute_reply":"2026-03-19T00:16:41.373661Z"}},"outputs":[],"execution_count":null}]}