{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"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\n# import numpy as np # linear algebra\n# import 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\n# import os\n# for 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\n\n# # Use the kagglehub client library to attach Kaggle resources like competitions, datasets, and models to your session\n# # Learn more about kagglehub: https://github.com/Kaggle/kagglehub/blob/main/README.md\n\n# import kagglehub\n# # kagglehub.dataset_download('<owner>/<dataset-slug>')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import keras\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom keras import layers\n\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay\nfrom sklearn.model_selection import train_test_split\nfrom keras.applications.resnet50 import ResNet50, preprocess_input","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:57:05.227105Z","iopub.execute_input":"2026-07-28T17:57:05.227584Z","iopub.status.idle":"2026-07-28T17:57:21.96592Z","shell.execute_reply.started":"2026-07-28T17:57:05.227517Z","shell.execute_reply":"2026-07-28T17:57:21.965059Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"keras.utils.set_random_seed(42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:57:21.968185Z","iopub.execute_input":"2026-07-28T17:57:21.968901Z","iopub.status.idle":"2026-07-28T17:57:21.972529Z","shell.execute_reply.started":"2026-07-28T17:57:21.96887Z","shell.execute_reply":"2026-07-28T17:57:21.971611Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/competitions/cifar-10/trainLabels.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:57:26.048096Z","iopub.execute_input":"2026-07-28T17:57:26.048728Z","iopub.status.idle":"2026-07-28T17:57:26.078571Z","shell.execute_reply.started":"2026-07-28T17:57:26.048687Z","shell.execute_reply":"2026-07-28T17:57:26.077616Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if df['label'].dtype == 'object':\n\n    label_names = sorted(df['label'].unique())\n    label_to_index = {name: i for i, name in enumerate(label_names)}\n    df['label_int'] = df['label'].map(label_to_index)\n    print(\"Done :\", label_names)\nelse:\n    df['label_int'] = df['label']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:57:32.317523Z","iopub.execute_input":"2026-07-28T17:57:32.318125Z","iopub.status.idle":"2026-07-28T17:57:32.339968Z","shell.execute_reply.started":"2026-07-28T17:57:32.318096Z","shell.execute_reply":"2026-07-28T17:57:32.339302Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['image_path'] = '/kaggle/working/train/' + df['id'].astype(str) + '.png'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:57:39.777104Z","iopub.execute_input":"2026-07-28T17:57:39.777576Z","iopub.status.idle":"2026-07-28T17:57:39.805497Z","shell.execute_reply.started":"2026-07-28T17:57:39.777506Z","shell.execute_reply":"2026-07-28T17:57:39.804931Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df, val_df = train_test_split(df, test_size=0.2, random_state=42, stratify=df['label_int'])\n\nprint(f\"📊 حجم بيانات التدريب: {len(train_df)} | حجم بيانات التحقق: {len(val_df)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:57:47.016894Z","iopub.execute_input":"2026-07-28T17:57:47.017771Z","iopub.status.idle":"2026-07-28T17:57:47.054882Z","shell.execute_reply.started":"2026-07-28T17:57:47.017729Z","shell.execute_reply":"2026-07-28T17:57:47.054118Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_and_parse_image(path, label):\n    image = tf.io.read_file(path)\n    image = tf.image.decode_png(image, channels=3)\n    image = tf.image.resize(image, [32, 32]) \n    \n    label_onehot = keras.ops.one_hot(label, num_classes=10)\n    \n    return image, label_onehot","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:58:09.537751Z","iopub.execute_input":"2026-07-28T17:58:09.53817Z","iopub.status.idle":"2026-07-28T17:58:09.543011Z","shell.execute_reply.started":"2026-07-28T17:58:09.538143Z","shell.execute_reply":"2026-07-28T17:58:09.542323Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataset = (\n    tf.data.Dataset.from_tensor_slices((train_df['image_path'].values, train_df['label_int'].values))\n    .shuffle(buffer_size=len(train_df))\n    .map(load_and_parse_image, num_parallel_calls=tf.data.AUTOTUNE)\n    .batch(64)\n    .prefetch(buffer_size=tf.data.AUTOTUNE)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:58:26.272337Z","iopub.execute_input":"2026-07-28T17:58:26.273076Z","iopub.status.idle":"2026-07-28T17:58:29.842302Z","shell.execute_reply.started":"2026-07-28T17:58:26.273046Z","shell.execute_reply":"2026-07-28T17:58:29.841692Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_dataset = (\n    tf.data.Dataset.from_tensor_slices((val_df['image_path'].values, val_df['label_int'].values))\n    .map(load_and_parse_image, num_parallel_calls=tf.data.AUTOTUNE)\n    .batch(64)\n    .prefetch(buffer_size=tf.data.AUTOTUNE)\n)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:58:38.106106Z","iopub.execute_input":"2026-07-28T17:58:38.106388Z","iopub.status.idle":"2026-07-28T17:58:38.134131Z","shell.execute_reply.started":"2026-07-28T17:58:38.106365Z","shell.execute_reply":"2026-07-28T17:58:38.133227Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"inputs = keras.Input(shape=(32, 32, 3))\n\n# أ) تكبير الصورة لتناسب ResNet50 (224x224)\nx = layers.Resizing(224, 224)(inputs)\n\n# ب) طبقات التغيير العشوائي (Data Augmentation) التي أضفتها أنت\nx = layers.RandomFlip(\"horizontal\")(x)\nx = layers.RandomRotation(factor=10 / 360, fill_mode=\"constant\", fill_value=0.0)(x)\nx = layers.RandomZoom(height_factor=0.1, width_factor=0.1, fill_mode=\"constant\", fill_value=0.0)(x)\n\n# ج) المعالجة الخاصة بـ ResNet50 بدلاً من (1.0 / 255.0)\nx = layers.Lambda(preprocess_input)(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T18:14:04.083862Z","iopub.execute_input":"2026-07-28T18:14:04.084606Z","iopub.status.idle":"2026-07-28T18:14:04.112727Z","shell.execute_reply.started":"2026-07-28T18:14:04.084576Z","shell.execute_reply":"2026-07-28T18:14:04.112157Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_model = ResNet50(\n    weights='imagenet',\n    include_top=False,\n    input_shape=(224, 224, 3)\n)\nbase_model.trainable = False  # تجميد الأوزان للمرحلة الأولى (Feature Extraction)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T18:14:22.120028Z","iopub.execute_input":"2026-07-28T18:14:22.120563Z","iopub.status.idle":"2026-07-28T18:14:24.023514Z","shell.execute_reply.started":"2026-07-28T18:14:22.120522Z","shell.execute_reply":"2026-07-28T18:14:24.022906Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = base_model(x, training=False)\n\n# هـ) رأس التصنيف الجديد (مشابه لما قمت بفي نموذجك اليدوي)\nx = layers.GlobalAveragePooling2D()(x)\nx = layers.Dense(256, use_bias=False)(x)\nx = layers.BatchNormalization()(x)\nx = layers.Activation(\"relu\")(x)\nx = layers.Dropout(0.5)(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T18:14:59.043685Z","iopub.execute_input":"2026-07-28T18:14:59.044102Z","iopub.status.idle":"2026-07-28T18:14:59.073324Z","shell.execute_reply.started":"2026-07-28T18:14:59.044074Z","shell.execute_reply":"2026-07-28T18:14:59.072758Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"outputs = layers.Dense(10, activation=\"softmax\")(x) # 10 فئات لـ CIFAR-10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T18:15:14.644757Z","iopub.execute_input":"2026-07-28T18:15:14.645221Z","iopub.status.idle":"2026-07-28T18:15:14.659063Z","shell.execute_reply.started":"2026-07-28T18:15:14.64519Z","shell.execute_reply":"2026-07-28T18:15:14.658339Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = keras.Model(inputs, outputs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T18:15:35.108812Z","iopub.execute_input":"2026-07-28T18:15:35.109234Z","iopub.status.idle":"2026-07-28T18:15:35.116844Z","shell.execute_reply.started":"2026-07-28T18:15:35.109204Z","shell.execute_reply":"2026-07-28T18:15:35.115951Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(\n    optimizer=keras.optimizers.Adam(learning_rate=1e-3),\n    loss='categorical_crossentropy',\n    metrics=['accuracy']\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T18:18:30.175094Z","iopub.execute_input":"2026-07-28T18:18:30.175892Z","iopub.status.idle":"2026-07-28T18:18:30.185934Z","shell.execute_reply.started":"2026-07-28T18:18:30.175855Z","shell.execute_reply":"2026-07-28T18:18:30.18514Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.fit(train_dataset, epochs=10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T18:18:37.258016Z","iopub.execute_input":"2026-07-28T18:18:37.258559Z","iopub.status.idle":"2026-07-28T18:46:01.631335Z","shell.execute_reply.started":"2026-07-28T18:18:37.258514Z","shell.execute_reply":"2026-07-28T18:46:01.630705Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# model = keras.Sequential([\n#         keras.Input(shape=(32, 32, 3)),\n        \n#         layers.Rescaling(scale=1.0 / 255.0), \n#         layers.RandomFlip(\"horizontal\"),     \n#         layers.RandomRotation(factor=10 / 360, fill_mode=\"constant\", fill_value=0.0),\n#         layers.RandomZoom(height_factor=0.1, width_factor=0.1, fill_mode=\"constant\", fill_value=0.0),\n\n#         layers.Conv2D(64, kernel_size=(3, 3), padding=\"same\", use_bias=False),\n#         layers.BatchNormalization(), \n#         layers.Activation(\"relu\"),\n#         layers.Conv2D(64, kernel_size=(3, 3), padding=\"same\", use_bias=False),\n#         layers.BatchNormalization(), \n#         layers.Activation(\"relu\"),\n#         layers.MaxPool2D(pool_size=(2, 2)), \n#         layers.Dropout(0.25),\n\n#         layers.Conv2D(128, kernel_size=(3, 3), padding=\"same\", use_bias=False),\n#         layers.BatchNormalization(), \n#         layers.Activation(\"relu\"),\n#         layers.Conv2D(128, kernel_size=(3, 3), padding=\"same\", use_bias=False),\n#         layers.BatchNormalization(), \n#         layers.Activation(\"relu\"),\n#         layers.MaxPool2D(pool_size=(2, 2)), \n#         layers.Dropout(0.35),\n        \n\n#         layers.Conv2D(256, kernel_size=(3, 3), padding=\"same\", use_bias=False),\n#         layers.BatchNormalization(), \n#         layers.Activation(\"relu\"),\n#         layers.MaxPool2D(pool_size=(2, 2)), \n#         layers.Dropout(0.45),\n        \n\n#         layers.Flatten(),\n#         layers.Dense(256, use_bias=False),\n#         layers.BatchNormalization(), \n#         layers.Activation(\"relu\"),\n        \n#         layers.Dropout(0.5),\n#         layers.Dense(10, activation=\"softmax\") # 10 فئات لـ CIFAR-10\n#     ])\n\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:58:45.994053Z","iopub.execute_input":"2026-07-28T17:58:45.99472Z","iopub.status.idle":"2026-07-28T17:58:46.962877Z","shell.execute_reply.started":"2026-07-28T17:58:45.994687Z","shell.execute_reply":"2026-07-28T17:58:46.962039Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-12T22:53:02.447239Z","iopub.execute_input":"2026-07-12T22:53:02.448143Z","iopub.status.idle":"2026-07-12T22:53:02.482206Z","shell.execute_reply.started":"2026-07-12T22:53:02.44811Z","shell.execute_reply":"2026-07-12T22:53:02.481572Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"batch_size = 64 \nepochs = 65","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:58:59.123144Z","iopub.execute_input":"2026-07-28T17:58:59.123884Z","iopub.status.idle":"2026-07-28T17:58:59.127526Z","shell.execute_reply.started":"2026-07-28T17:58:59.123855Z","shell.execute_reply":"2026-07-28T17:58:59.126776Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# lr_scheduler = keras.callbacks.ReduceLROnPlateau(\n#     monitor='val_loss',  # مراقبة خسارة التحقق\n#     factor=0.5,          # خفض الـ LR بمقدار النصف (LR = LR * 0.5)\n#     patience=3,          # الانتظار لـ 3 حقبات قبل الخفض\n#     min_lr=1e-6,         # الحد الأدنى الذي لا ينزل عنه\n#     verbose=1            # إبلاغك عند كل عملية خفض\n# )","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# model.compile(\n#     optimizer=keras.optimizers.Adam(learning_rate=0.001),\n#     loss=keras.losses.CategoricalCrossentropy(label_smoothing=0.1),\n#     metrics=[\"accuracy\"]\n# )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:59:05.757397Z","iopub.execute_input":"2026-07-28T17:59:05.757771Z","iopub.status.idle":"2026-07-28T17:59:05.77198Z","shell.execute_reply.started":"2026-07-28T17:59:05.757738Z","shell.execute_reply":"2026-07-28T17:59:05.771293Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# history = model.fit(\n#     train_dataset,\n#     validation_data=val_dataset,\n#     epochs=100, \n#     callbacks=[\n#         keras.callbacks.EarlyStopping(monitor=\"val_loss\", patience=10, restore_best_weights=True),\n#         keras.callbacks.ReduceLROnPlateau(monitor=\"val_loss\", factor=0.5, patience=3, verbose=1)\n#     ]\n# )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-28T17:59:18.523856Z","iopub.execute_input":"2026-07-28T17:59:18.524273Z","iopub.status.idle":"2026-07-28T18:13:06.757309Z","shell.execute_reply.started":"2026-07-28T17:59:18.524245Z","shell.execute_reply":"2026-07-28T18:13:06.756678Z"}},"outputs":[],"execution_count":null}]}