{"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":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"_uuid":"af3f4537-d0fa-43c3-8ace-149ea91e86c1","_cell_guid":"752a1435-addc-46be-94a0-c2495f1ad108","trusted":true,"collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2025-07-23T10:01:11.735931Z","iopub.execute_input":"2025-07-23T10:01:11.736519Z","iopub.status.idle":"2025-07-23T10:01:12.061277Z","shell.execute_reply.started":"2025-07-23T10:01:11.736493Z","shell.execute_reply":"2025-07-23T10:01:12.059820Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install py7zr","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:01:14.882870Z","iopub.execute_input":"2025-07-23T10:01:14.883682Z","iopub.status.idle":"2025-07-23T10:01:22.464550Z","shell.execute_reply.started":"2025-07-23T10:01:14.883656Z","shell.execute_reply":"2025-07-23T10:01:22.463468Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import py7zr\n\nos.makedirs('/kaggle/temp/train', exist_ok=True)\nos.makedirs('/kaggle/temp/test', exist_ok=True)\n\n# Extract TRAIN data\nwith py7zr.SevenZipFile('../input/cifar-10/train.7z', mode='r') as archive_train:\n    archive_train.extractall(path='/kaggle/temp/train')\n\n# Extract TEST data\nwith py7zr.SevenZipFile('../input/cifar-10/test.7z', mode='r') as archive_test:\n    archive_test.extractall(path='/kaggle/temp/test')\n\nprint(\"Extraction complete!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:01:22.466215Z","iopub.execute_input":"2025-07-23T10:01:22.466485Z","iopub.status.idle":"2025-07-23T10:04:11.570563Z","shell.execute_reply.started":"2025-07-23T10:01:22.466459Z","shell.execute_reply":"2025-07-23T10:04:11.569751Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Train files:\", len(os.listdir('/kaggle/temp/train/train')))\nprint(\"Test files:\", len(os.listdir('/kaggle/temp/test/test'))) ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:04:30.872780Z","iopub.execute_input":"2025-07-23T10:04:30.873629Z","iopub.status.idle":"2025-07-23T10:04:31.072146Z","shell.execute_reply.started":"2025-07-23T10:04:30.873584Z","shell.execute_reply":"2025-07-23T10:04:31.070848Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\nlabels_df = pd.read_csv('/kaggle/input/cifar-10/trainLabels.csv')\nprint(labels_df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:04:33.485707Z","iopub.execute_input":"2025-07-23T10:04:33.486103Z","iopub.status.idle":"2025-07-23T10:04:33.531539Z","shell.execute_reply.started":"2025-07-23T10:04:33.486079Z","shell.execute_reply":"2025-07-23T10:04:33.530797Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom PIL import Image\nimport os\nfrom tqdm import tqdm\n\ntrain_dir = '/kaggle/temp/train/train'\nx_train = []\ny_train = []\n\nfor idx, row in tqdm(labels_df.iterrows(), total=labels_df.shape[0]):\n    img_id = row['id']\n    label = row['label']\n    img_path = os.path.join(train_dir, f\"{img_id}.png\")\n    img = Image.open(img_path)\n    img = np.array(img)\n    x_train.append(img)\n    y_train.append(label)\n\nx_train = np.array(x_train)\ny_train = np.array(y_train)\nprint(x_train.shape, y_train.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:04:35.602006Z","iopub.execute_input":"2025-07-23T10:04:35.602571Z","iopub.status.idle":"2025-07-23T10:04:50.581786Z","shell.execute_reply.started":"2025-07-23T10:04:35.602535Z","shell.execute_reply":"2025-07-23T10:04:50.581120Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nfrom tensorflow.keras.utils import to_categorical\n\ni = 56\nplt.imshow(x_train[i])\nplt.title(f\"Label: {y_train[i]}\")\nplt.axis('off')\nplt.show()\nx_train = x_train.astype('float32') / 255.0\nprint(x_train[1])\n\nle = LabelEncoder()\ny_train_int = le.fit_transform(y_train)\ny_train_onehot = to_categorical(y_train_int, num_classes=10)\nprint(y_train_onehot.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:04:54.412368Z","iopub.execute_input":"2025-07-23T10:04:54.412924Z","iopub.status.idle":"2025-07-23T10:05:14.696450Z","shell.execute_reply.started":"2025-07-23T10:04:54.412897Z","shell.execute_reply":"2025-07-23T10:05:14.695522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import layers, models\n\nmodel = models.Sequential([\n    layers.Conv2D(32, (3,3), activation='relu', input_shape=(32,32,3)),\n    layers.BatchNormalization(),\n    layers.Conv2D(32, (3,3), activation='relu'),\n    layers.MaxPooling2D((2,2)),\n    layers.Dropout(0.2),\n\n    \n    layers.Conv2D(64, (3,3), activation='relu'),\n    layers.BatchNormalization(),\n    layers.Conv2D(64, (3,3), activation='relu'),\n    layers.MaxPooling2D((2,2)),\n    layers.Dropout(0.3),\n\n    layers.Flatten(),\n    layers.Dense(256, activation='relu'),\n    layers.Dropout(0.5),\n    layers.Dense(10, activation='softmax')\n])\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:05:14.697916Z","iopub.execute_input":"2025-07-23T10:05:14.699168Z","iopub.status.idle":"2025-07-23T10:05:18.415712Z","shell.execute_reply.started":"2025-07-23T10:05:14.699133Z","shell.execute_reply":"2025-07-23T10:05:18.415020Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss='categorical_crossentropy',\n    metrics=['accuracy']\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:05:24.675538Z","iopub.execute_input":"2025-07-23T10:05:24.676329Z","iopub.status.idle":"2025-07-23T10:05:24.690790Z","shell.execute_reply.started":"2025-07-23T10:05:24.676303Z","shell.execute_reply":"2025-07-23T10:05:24.690053Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    x_train, y_train_onehot,\n    batch_size=64,\n    epochs=20,\n    validation_split=0.2 \n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:05:27.339975Z","iopub.execute_input":"2025-07-23T10:05:27.340278Z","iopub.status.idle":"2025-07-23T10:06:58.958167Z","shell.execute_reply.started":"2025-07-23T10:05:27.340260Z","shell.execute_reply":"2025-07-23T10:06:58.957378Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dir = '/kaggle/temp/test/test'\ntest_files = sorted(\n    [f for f in os.listdir(test_dir) if f.endswith('.png')],\n    key=lambda x: int(x.split('.')[0])  # Sort by numeric ID\n)\n\nx_test = []\nfor fname in tqdm(test_files):\n    img_path = os.path.join(test_dir, fname)\n    img = Image.open(img_path)\n    img = np.array(img).astype('float32') / 255.0  # Normalize here\n    x_test.append(img)\n\nx_test = np.array(x_test)\n\n\n# Predict\npredictions = model.predict(x_test)\npredicted_labels = np.argmax(predictions, axis=1)  # Shape: (300000,)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:07:03.732198Z","iopub.execute_input":"2025-07-23T10:07:03.732480Z","iopub.status.idle":"2025-07-23T10:08:43.480692Z","shell.execute_reply.started":"2025-07-23T10:07:03.732462Z","shell.execute_reply":"2025-07-23T10:08:43.479946Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom collections import Counter\n\n# Make predictions\npredictions = model.predict(x_test)\npredicted_labels = np.argmax(predictions, axis=1)\npredicted_class_names = le.inverse_transform(predicted_labels)  # Decode labels using LabelEncoder\n\n# Display multiple test images with predicted labels in a grid\nnum_images_to_display = 25  # Adjust this number as needed\nrows, cols = 5, 5  # 5x5 grid\nplt.figure(figsize=(15, 15))  # Adjust figure size for better visibility\nfor i in range(min(num_images_to_display, len(x_test))):\n    plt.subplot(rows, cols, i + 1)\n    plt.imshow(x_test[i])\n    plt.title(f\"Predicted: {predicted_class_names[i]}\", fontsize=10)\n    plt.axis('off')\nplt.tight_layout()  # Adjust spacing between subplots\nplt.show()\n\n# Count predictions for each class\npred_counts = Counter(predicted_class_names)\nclass_names = list(pred_counts.keys())\ncounts = list(pred_counts.values())\n\n# Create a bar chart for prediction distribution\n{\n  \"type\": \"bar\",\n  \"data\": {\n    \"labels\": class_names,\n    \"datasets\": [{\n      \"label\": \"Prediction Distribution\",\n      \"data\": counts,\n      \"backgroundColor\": [\"#FF6F61\", \"#6B5B95\", \"#88B04B\", \"#F7CAC9\", \"#92A8D1\", \"#955251\", \"#B565A7\", \"#009B77\", \"#DD4124\", \"#D65076\"],\n      \"borderColor\": [\"#D64550\", \"#5A4A78\", \"#618A3D\", \"#D9A7B0\", \"#7A8EB1\", \"#7A3E3E\", \"#8B4A8E\", \"#007B5F\", \"#B3311F\", \"#B03A5E\"],\n      \"borderWidth\": 1\n    }]\n  },\n  \"options\": {\n    \"scales\": {\n      \"y\": {\n        \"beginAtZero\": True,\n        \"title\": {\n          \"display\": True,\n          \"text\": \"Number of Predictions\"\n        }\n      },\n      \"x\": {\n        \"title\": {\n          \"display\": True,\n          \"text\": \"Class\"\n        }\n      }\n    },\n    \"plugins\": {\n      \"legend\": {\n        \"display\": False\n      },\n      \"title\": {\n        \"display\": True,\n        \"text\": \"Distribution of Predicted Classes\"\n      }\n    }\n  }\n}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-23T10:15:51.344244Z","iopub.execute_input":"2025-07-23T10:15:51.344680Z","iopub.status.idle":"2025-07-23T10:16:27.075731Z","shell.execute_reply.started":"2025-07-23T10:15:51.344655Z","shell.execute_reply":"2025-07-23T10:16:27.074836Z"}},"outputs":[],"execution_count":null}]}