{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":31012,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install -q py7zr\n\nimport os, py7zr, pandas as pd, numpy as np\nfrom PIL import Image\nfrom tqdm.auto import tqdm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models, callbacks\nimport matplotlib.pyplot as plt\n\n# 1️⃣ Extract train.7z if you haven’t already\npy7zr.SevenZipFile(\"/kaggle/input/cifar-10/train.7z\", mode='r')\\\n     .extractall(path=\"/kaggle/working/train\")\n\n# 2️⃣ Read labels and convert class names to integers\nlabels_df = pd.read_csv(\"/kaggle/input/cifar-10/trainLabels.csv\")\nle = LabelEncoder()\nlabels_df[\"label\"] = le.fit_transform(labels_df[\"label\"])  # Fix applied here\n\n# 3️⃣ Load images and labels\ndef load_images(df, folder):\n    X, y = [], []\n    for img_id, lbl in tqdm(df.values, desc=\"Loading images\"):\n        img = Image.open(f\"{folder}/{img_id}.png\").resize((32, 32))\n        X.append(np.array(img))\n        y.append(lbl)\n    return np.stack(X), np.array(y, dtype='int32')\n\nx, y = load_images(labels_df, \"/kaggle/working/train/train\")\nx = x.astype('float32') / 255.0\nx_tr, x_val, y_tr, y_val = train_test_split(x, y, test_size=0.1,\n                                            stratify=y, random_state=42)\n\n# 4️⃣ Build & compile model\nmodel = models.Sequential([\n    layers.Input(shape=(32, 32, 3)),\n    layers.Conv2D(32, 3, activation='relu'),\n    layers.MaxPooling2D(),\n    layers.Conv2D(64, 3, activation='relu'),\n    layers.MaxPooling2D(),\n    layers.Conv2D(128, 3, activation='relu'),\n    layers.Flatten(),\n    layers.Dense(128, activation='relu'),\n    layers.Dropout(0.5),\n    layers.Dense(10, activation='softmax'),\n])\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\nes = callbacks.EarlyStopping(monitor='val_loss', patience=3,\n                             restore_best_weights=True)\n\n# 5️⃣ Train\nprint(\"GPU available:\", tf.config.list_physical_devices('GPU'))\nhistory = model.fit(x_tr, y_tr,\n                    validation_data=(x_val, y_val),\n                    epochs=20, batch_size=64,\n                    callbacks=[es], verbose=2)\n\n# 6️⃣ Plot\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'], label='train')\nplt.plot(history.history['val_loss'], label='val')\nplt.title('Loss'); plt.legend()\nplt.subplot(1, 2, 2)\nplt.plot(history.history['accuracy'], label='train')\nplt.plot(history.history['val_accuracy'], label='val')\nplt.title('Accuracy'); plt.legend()\nplt.show()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T07:48:43.085590Z","iopub.execute_input":"2025-05-09T07:48:43.086409Z","iopub.status.idle":"2025-05-09T07:49:53.446989Z","shell.execute_reply.started":"2025-05-09T07:48:43.086386Z","shell.execute_reply":"2025-05-09T07:49:53.446067Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import py7zr\nimport os\n\n# Only extract if not already done\nif not os.path.exists(\"/kaggle/working/test\"):\n    with py7zr.SevenZipFile(\"/kaggle/input/cifar-10/test.7z\", mode='r') as archive:\n        archive.extractall(path=\"/kaggle/working/test\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T07:56:27.953503Z","iopub.execute_input":"2025-05-09T07:56:27.953759Z","iopub.status.idle":"2025-05-09T07:58:29.764197Z","shell.execute_reply.started":"2025-05-09T07:56:27.953730Z","shell.execute_reply":"2025-05-09T07:58:29.763591Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfrom PIL import Image\nimport numpy as np\n\ntest_dir = \"/kaggle/working/test/test\"\ntest_images = []\n\nif not os.path.exists(test_dir):\n    raise FileNotFoundError(f\"{test_dir} does not exist. Check extraction path.\")\n\nimage_files = [f for f in os.listdir(test_dir) if f.endswith(\".png\") and f.split('.')[0].isdigit()]\nimage_files = sorted(image_files, key=lambda x: int(x.split('.')[0]))\n\n# Load and preprocess\nfor img_file in image_files:\n    img_path = os.path.join(test_dir, img_file)\n    img = Image.open(img_path).resize((32, 32))\n    img_array = np.array(img).astype('float32') / 255.0\n    test_images.append(img_array)\n\nX_test = np.array(test_images)\nprint(f\"Loaded {len(X_test)} test images.\")\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T08:14:59.152543Z","iopub.execute_input":"2025-05-09T08:14:59.153249Z","iopub.status.idle":"2025-05-09T08:15:49.066633Z","shell.execute_reply.started":"2025-05-09T08:14:59.153225Z","shell.execute_reply":"2025-05-09T08:15:49.066000Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\npredictions = model.predict(X_test)\npredicted_classes = np.argmax(predictions, axis=1)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T08:18:02.435445Z","iopub.execute_input":"2025-05-09T08:18:02.435716Z","iopub.status.idle":"2025-05-09T08:18:29.290919Z","shell.execute_reply.started":"2025-05-09T08:18:02.435699Z","shell.execute_reply":"2025-05-09T08:18:29.290308Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\nfile_names = [f\"{i}.png\" for i in range(1, len(predicted_classes) + 1)]\n\n# Create DataFrame\nsubmission_df = pd.DataFrame({\n    \"Id\": file_names,\n    \"Label\": predicted_classes\n})\n\nsubmission_df.to_csv(\"submission.csv\", index=False)\nprint(\"✅ submission.csv created successfully.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T08:18:42.098948Z","iopub.execute_input":"2025-05-09T08:18:42.099663Z","iopub.status.idle":"2025-05-09T08:18:42.376618Z","shell.execute_reply.started":"2025-05-09T08:18:42.099639Z","shell.execute_reply":"2025-05-09T08:18:42.375834Z"}},"outputs":[],"execution_count":null}]}