{"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\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\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\nimport kagglehub\n# kagglehub.dataset_download('<owner>/<dataset-slug>')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-09-22T11:48:36.541968Z","iopub.execute_input":"2026-09-22T11:48:36.542312Z","iopub.status.idle":"2026-09-22T11:48:38.630064Z","shell.execute_reply.started":"2026-09-22T11:48:36.542288Z","shell.execute_reply":"2026-09-22T11:48:38.629264Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import py7zr\n\n# We are using the exact path you just found\nfile_path = '/kaggle/input/competitions/cifar-10/test.7z'\n\nwith py7zr.SevenZipFile(file_path, mode='r') as z:\n    z.extractall()\n\nprint(\"Extraction complete!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-22T11:58:07.985596Z","iopub.execute_input":"2026-09-22T11:58:07.986333Z","iopub.status.idle":"2026-09-22T12:01:33.483284Z","shell.execute_reply.started":"2026-09-22T11:58:07.986304Z","shell.execute_reply":"2026-09-22T12:01:33.482227Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import glob\nprint(len(glob.glob('test/*')))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-22T12:02:42.725743Z","iopub.execute_input":"2026-09-22T12:02:42.726658Z","iopub.status.idle":"2026-09-22T12:02:43.22459Z","shell.execute_reply.started":"2026-09-22T12:02:42.726628Z","shell.execute_reply":"2026-09-22T12:02:43.223902Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-22T12:06:24.743057Z","iopub.execute_input":"2026-09-22T12:06:24.743638Z","iopub.status.idle":"2026-09-22T12:49:21.401123Z","shell.execute_reply.started":"2026-09-22T12:06:24.74361Z","shell.execute_reply":"2026-09-22T12:49:21.40043Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models, regularizers\nimport numpy as np\nimport pandas as pd\nimport os\nimport glob\nfrom PIL import Image\n\n# Load CIFAR-10 data\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()\n\n# Normalize pixel values to be between 0 and 1\nx_train = x_train.astype('float32') / 255.0\nx_test = x_test.astype('float32') / 255.0\n\n# Data Augmentation: This randomly flips and shifts images during training to prevent overfitting\ndata_augmentation = tf.keras.Sequential([\n    layers.RandomFlip(\"horizontal\"),\n    layers.RandomRotation(0.1),\n    layers.RandomZoom(0.1),\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-22T12:54:12.036269Z","iopub.execute_input":"2026-09-22T12:54:12.037027Z","iopub.status.idle":"2026-09-22T12:54:16.674266Z","shell.execute_reply.started":"2026-09-22T12:54:12.036995Z","shell.execute_reply":"2026-09-22T12:54:16.67352Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def residual_block(x, filters, stride=1):\n    shortcut = x\n    \n    # First convolution\n    x = layers.Conv2D(filters, (3, 3), strides=stride, padding='same')(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Activation('relu')(x)\n    \n    # Second convolution\n    x = layers.Conv2D(filters, (3, 3), strides=1, padding='same')(x)\n    x = layers.BatchNormalization()(x)\n    \n    # If the number of filters changed or we strided, we need to adjust the shortcut\n    if stride != 1 or shortcut.shape[-1] != filters:\n        shortcut = layers.Conv2D(filters, (1, 1), strides=stride, padding='same')(shortcut)\n        shortcut = layers.BatchNormalization()(shortcut)\n    \n    # Add the shortcut to the main path (the \"Residual\" connection)\n    x = layers.Add()([x, shortcut])\n    x = layers.Activation('relu')(x)\n    return x\n\ndef build_resnet(input_shape=(32, 32, 3), num_classes=10):\n    inputs = layers.Input(shape=input_shape)\n    x = data_augmentation(inputs)\n    \n    # Initial Conv Layer\n    x = layers.Conv2D(64, (3, 3), padding='same')(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Activation('relu')(x)\n    \n    # ResNet Blocks\n    x = residual_block(x, 64, stride=1)\n    x = residual_block(x, 64, stride=1)\n    \n    x = residual_block(x, 128, stride=2) # Downsample\n    x = residual_block(x, 128, stride=1)\n    \n    x = residual_block(x, 256, stride=2) # Downsample\n    x = residual_block(x, 256, stride=1)\n    \n    # Global Average Pooling and Output\n    x = layers.GlobalAveragePooling2D()(x)\n    outputs = layers.Dense(num_classes, activation='softmax')(x)\n    \n    model = models.Model(inputs, outputs)\n    return model\n\nmodel = build_resnet()\nmodel.summary() # This will print the architecture for your report","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-22T12:55:55.555363Z","iopub.execute_input":"2026-09-22T12:55:55.555909Z","iopub.status.idle":"2026-09-22T12:55:57.326793Z","shell.execute_reply.started":"2026-09-22T12:55:55.555825Z","shell.execute_reply":"2026-09-22T12:55:57.326281Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile the model\nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),\n    loss='sparse_categorical_crossentropy',\n    metrics=['accuracy']\n)\n\n# Train the model\n# We use a learning rate scheduler to lower the learning rate if accuracy stops improving\nlr_scheduler = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy', patience=5, factor=0.5, min_lr=1e-5)\nearly_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=15, restore_best_weights=True)\n\nhistory = model.fit(\n    x_train, y_train,\n    epochs=50, # It will likely stop earlier due to early stopping\n    batch_size=128,\n    validation_data=(x_test, y_test),\n    callbacks=[lr_scheduler, early_stopping]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-22T12:57:23.673279Z","iopub.execute_input":"2026-09-22T12:57:23.67409Z","iopub.status.idle":"2026-09-22T13:45:36.533736Z","shell.execute_reply.started":"2026-09-22T12:57:23.67406Z","shell.execute_reply":"2026-09-22T13:45:36.533134Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport glob\nfrom PIL import Image\nimport tensorflow as tf\n\n# 1. Get all image paths\ntest_dir = 'test'\nimage_paths = sorted(glob.glob(os.path.join(test_dir, '*')), key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))\n\n# 2. Create a function to load and preprocess a single image\ndef load_and_preprocess_image(path):\n    # THE FIX: Convert the TensorFlow Tensor back to a string\n    path = path.numpy().decode('utf-8') \n    \n    img = Image.open(path).convert('RGB')\n    img = img.resize((32, 32))\n    img_array = np.array(img).astype('float32') / 255.0\n    return img_array\n\n# 3. Create a TensorFlow Dataset for efficient loading\ntest_ds = tf.data.Dataset.from_tensor_slices(image_paths)\ntest_ds = test_ds.map(lambda x: tf.py_function(load_and_preprocess_image, [x], tf.float32), num_parallel_calls=tf.data.AUTOTUNE)\ntest_ds = test_ds.batch(256).prefetch(tf.data.AUTOTUNE)\n\n# 4. Predict\nprint(\"Predicting on 300,000 images. This will take a few minutes...\")\npredictions = model.predict(test_ds)\npredicted_labels = np.argmax(predictions, axis=1)\n\n# 5. Extract IDs and create the dataframe\nids = [int(os.path.splitext(os.path.basename(path))[0]) for path in image_paths]\nsubmission = pd.DataFrame({'id': ids, 'label': predicted_labels})\n\n# 6. Save to CSV\nsubmission.to_csv('submission.csv', index=False)\nprint(\"Submission file created successfully! Look for 'submission.csv' in the file browser on the left.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-22T13:51:51.982602Z","iopub.execute_input":"2026-09-22T13:51:51.98304Z","iopub.status.idle":"2026-09-22T13:58:20.129998Z","shell.execute_reply.started":"2026-09-22T13:51:51.983012Z","shell.execute_reply":"2026-09-22T13:58:20.129252Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!kaggle competitions submit -c cifar-10 -f submission.csv -m \"ResNet from scratch\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-22T14:16:48.710467Z","iopub.execute_input":"2026-09-22T14:16:48.710745Z","iopub.status.idle":"2026-09-22T14:16:51.507918Z","shell.execute_reply.started":"2026-09-22T14:16:48.710723Z","shell.execute_reply":"2026-09-22T14:16:51.507182Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n# This will search through all your input folders and print every file it finds\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        if filename.endswith('.7z') or filename.endswith('.csv'):\n            print(os.path.join(dirname, filename))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-22T11:56:53.448497Z","iopub.execute_input":"2026-09-22T11:56:53.449312Z","iopub.status.idle":"2026-09-22T11:56:53.456282Z","shell.execute_reply.started":"2026-09-22T11:56:53.449283Z","shell.execute_reply":"2026-09-22T11:56:53.455318Z"}},"outputs":[],"execution_count":null}]}