{"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":"gpu","dataSources":[{"sourceType":"competition","sourceId":3649,"databundleVersionId":46718}],"dockerImageVersionId":31287,"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,"execution":{"iopub.status.busy":"2026-03-15T22:19:45.792907Z","iopub.execute_input":"2026-03-15T22:19:45.793207Z","iopub.status.idle":"2026-03-15T22:19:47.523518Z","shell.execute_reply.started":"2026-03-15T22:19:45.793176Z","shell.execute_reply":"2026-03-15T22:19:47.522826Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir('/kaggle/input/competitions/cifar-10'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T22:21:39.792982Z","iopub.execute_input":"2026-03-15T22:21:39.793591Z","iopub.status.idle":"2026-03-15T22:21:39.799467Z","shell.execute_reply.started":"2026-03-15T22:21:39.793558Z","shell.execute_reply":"2026-03-15T22:21:39.798803Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install py7zr","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T22:24:32.117197Z","iopub.execute_input":"2026-03-15T22:24:32.117803Z","iopub.status.idle":"2026-03-15T22:26:38.060660Z","shell.execute_reply.started":"2026-03-15T22:24:32.117776Z","shell.execute_reply":"2026-03-15T22:26:38.059799Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import py7zr\n\n# Extract train\nwith py7zr.SevenZipFile('/kaggle/input/competitions/cifar-10/train.7z', 'r') as z:\n    z.extractall('/kaggle/working/')\nprint('Train extracted!')\n\n# Extract test  \nwith py7zr.SevenZipFile('/kaggle/input/competitions/cifar-10/test.7z', 'r') as z:\n    z.extractall('/kaggle/working/')\nprint('Test extracted!')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T22:26:55.025486Z","iopub.execute_input":"2026-03-15T22:26:55.025810Z","iopub.status.idle":"2026-03-15T22:29:38.484038Z","shell.execute_reply.started":"2026-03-15T22:26:55.025779Z","shell.execute_reply":"2026-03-15T22:29:38.483375Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(os.listdir('/kaggle/working/train')[:5])\nprint('Train images:', len(os.listdir('/kaggle/working/train')))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T22:29:44.352357Z","iopub.execute_input":"2026-03-15T22:29:44.352670Z","iopub.status.idle":"2026-03-15T22:29:44.431087Z","shell.execute_reply.started":"2026-03-15T22:29:44.352617Z","shell.execute_reply":"2026-03-15T22:29:44.430502Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\n\n# Extract files using py7zr\nimport py7zr\n\nwith py7zr.SevenZipFile('/kaggle/input/competitions/cifar-10/train.7z', 'r') as z:\n    z.extractall('/kaggle/working/')\nprint('Train extracted!')\n\nwith py7zr.SevenZipFile('/kaggle/input/competitions/cifar-10/test.7z', 'r') as z:\n    z.extractall('/kaggle/working/')\nprint('Test extracted!')\n\n# File lists\nfilename = os.listdir('/kaggle/working/train')\nprint(type(filename))\nprint(len(filename))\nprint(filename[0:5])\nprint(filename[-5:])\n\nfilename1 = os.listdir('/kaggle/working/test')\nprint(type(filename1))\nprint(len(filename1))\nprint(filename1[0:5])\nprint(filename1[-5:])\n\n# Labels processing\nlabels_df = pd.read_csv('/kaggle/input/competitions/cifar-10/trainLabels.csv')\nprint(labels_df.head())\nprint(labels_df.tail())\nprint(labels_df.shape)\nprint(labels_df[labels_df['id'] == 7796])\nprint(labels_df.head(10))\nprint(labels_df.tail(10))\nprint(labels_df['label'].value_counts())\n\nlabels_dictionary = {'airplane':0, 'automobile':1, 'bird':2, 'cat':3,\n                     'deer':4, 'dog':5, 'frog':6, 'horse':7, 'ship':8, 'truck':9}\nlabels = [labels_dictionary[i] for i in labels_df['label']]\nprint(labels[0:5])\nprint(labels[-5:])\n\n# Displaying sample image\nimport cv2\nimg = cv2.imread('/kaggle/working/train/7796.png')\nplt.imshow(img)\nplt.title('Sample Image')\nplt.axis('off')\nplt.show()\nprint(labels_df[labels_df['id'] == 7796])\n\nimg = cv2.imread('/kaggle/working/train/9998.png')\nplt.imshow(img)\nplt.title('Sample Image')\nplt.axis('off')\nplt.show()\nprint(labels_df[labels_df['id'] == 9998])\n\nid_list = list(labels_df['id'])\nprint(id_list[0:5])\nprint(id_list[-5:])\n\n# Convert images to numpy arrays\ntrain_data_folder = '/kaggle/working/train'\ndata = []\nfor id in id_list:\n    img_path = os.path.join(train_data_folder, str(id) + '.png')\n    image = Image.open(img_path)\n    image = np.array(image)\n    data.append(image)\n\nprint(type(data))\nprint(len(data))\nprint(type(data[0]))\nprint(data[0].shape)\n\n# Convert to numpy arrays\nX = np.array(data)\nY = np.array(labels)\nprint(X.shape)\nprint(Y.shape)\n\n# Train test split\nX_train, X_test, Y_train, Y_test = train_test_split(\n    X, Y, test_size=0.2, random_state=2)\nprint(X.shape, X_train.shape, X_test.shape)\n\n# Scaling\nX_train_scaled = X_train / 255\nX_test_scaled = X_test / 255\n\n# Simple Neural Network\nimport tensorflow as tf\nfrom tensorflow import keras\n\nnum_of_classes = 10\nmodel = keras.Sequential([\n    keras.layers.Flatten(input_shape=(32,32,3)),\n    keras.layers.Dense(64, activation='relu'),\n    keras.layers.Dense(num_of_classes, activation='softmax')\n])\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['acc'])\nmodel.fit(X_train_scaled, Y_train,\n          validation_split=0.1, epochs=10)\n\n# ResNet50\nfrom tensorflow.keras import models, layers, optimizers\nfrom tensorflow.keras.applications.resnet50 import ResNet50\n\nconvolutional_base = ResNet50(weights='imagenet',\n                               include_top=False,\n                               input_shape=(256,256,3))\nconvolutional_base.trainable = False\nprint(convolutional_base.summary())\n\nnum_of_classes = 10\nmodel = models.Sequential()\nmodel.add(layers.UpSampling2D((2,2)))\nmodel.add(layers.UpSampling2D((2,2)))\nmodel.add(layers.UpSampling2D((2,2)))\nmodel.add(convolutional_base)\nmodel.add(layers.Flatten())\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.Dense(128, activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.Dense(64, activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.Dense(num_of_classes, activation='relu'))\n\nmodel.compile(optimizer=optimizers.RMSprop(learning_rate=2e-5),\n              loss='sparse_categorical_crossentropy',\n              metrics=['acc'])\n\nhistory = model.fit(X_train_scaled, Y_train,\n                    validation_split=0.1,\n                    epochs=10)\n\n# Plot loss\nh = history\nplt.plot(h.history['loss'], label='train loss')\nplt.plot(h.history['val_loss'], label='validation loss')\nplt.legend()\nplt.show()\n\n# Plot accuracy\nplt.plot(h.history['acc'], label='train accuracy')\nplt.plot(h.history['val_acc'], label='validation accuracy')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T22:33:13.247042Z","iopub.execute_input":"2026-03-15T22:33:13.247824Z","iopub.status.idle":"2026-03-15T22:48:18.896607Z","shell.execute_reply.started":"2026-03-15T22:33:13.247791Z","shell.execute_reply":"2026-03-15T22:48:18.895853Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('/kaggle/working/cifar10_model.h5')\nprint('Model saved!')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T22:49:07.847112Z","iopub.execute_input":"2026-03-15T22:49:07.847947Z","iopub.status.idle":"2026-03-15T22:49:08.588422Z","shell.execute_reply.started":"2026-03-15T22:49:07.847914Z","shell.execute_reply":"2026-03-15T22:49:08.587684Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.path.exists('/kaggle/working/cifar10_model.h5'))\n# Should print: True","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T22:53:17.244992Z","iopub.execute_input":"2026-03-15T22:53:17.245749Z","iopub.status.idle":"2026-03-15T22:53:17.249672Z","shell.execute_reply.started":"2026-03-15T22:53:17.245721Z","shell.execute_reply":"2026-03-15T22:53:17.248917Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nsize = os.path.getsize('/kaggle/working/cifar10_model.h5')\nprint(f'Model size: {size/1024/1024:.1f} MB')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T22:56:41.332818Z","iopub.execute_input":"2026-03-15T22:56:41.333551Z","iopub.status.idle":"2026-03-15T22:56:41.337460Z","shell.execute_reply.started":"2026-03-15T22:56:41.333524Z","shell.execute_reply":"2026-03-15T22:56:41.336824Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import shutil\n\n# Copy to output folder\nshutil.copy('/kaggle/working/cifar10_model.h5', \n            '/kaggle/working/cifar10_model_copy.h5')\nprint('Done!')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T23:43:27.834945Z","iopub.execute_input":"2026-03-15T23:43:27.835660Z","iopub.status.idle":"2026-03-15T23:43:28.142211Z","shell.execute_reply.started":"2026-03-15T23:43:27.835624Z","shell.execute_reply":"2026-03-15T23:43:28.141272Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n# Check if file is there\nprint(os.path.getsize('/kaggle/working/cifar10_model.h5'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-15T23:45:55.696216Z","iopub.execute_input":"2026-03-15T23:45:55.696494Z","iopub.status.idle":"2026-03-15T23:45:55.700745Z","shell.execute_reply.started":"2026-03-15T23:45:55.696471Z","shell.execute_reply":"2026-03-15T23:45:55.700165Z"}},"outputs":[],"execution_count":null}]}