{"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":"import os, tensorflow as tf\nprint(os.listdir('/kaggle/input/competitions/cifar-10'))\nprint('GPU:', tf.config.list_physical_devices('GPU'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-23T17:23:59.673391Z","iopub.execute_input":"2026-09-23T17:23:59.673898Z","iopub.status.idle":"2026-09-23T17:24:01.217723Z","shell.execute_reply.started":"2026-09-23T17:23:59.673867Z","shell.execute_reply":"2026-09-23T17:24:01.216969Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install -q py7zr\nimport py7zr\n\nwith py7zr.SevenZipFile('/kaggle/input/competitions/cifar-10/test.7z', mode='r') as archive:\n    archive.extractall(path='/kaggle/working')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-23T17:24:01.219234Z","iopub.execute_input":"2026-09-23T17:24:01.219517Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.utils import to_categorical\n\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\nX_train, X_test = X_train / 255.0, X_test / 255.0\ny_train_cat, y_test_cat = to_categorical(y_train, 10), to_categorical(y_test, 10)\n\nCLASS_NAMES = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n               'dog', 'frog', 'horse', 'ship', 'truck']","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndatagen = ImageDataGenerator(rotation_range=15, width_shift_range=0.1,\n                              height_shift_range=0.1, horizontal_flip=True)\ndatagen.fit(X_train)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import layers, models\n\nmodel = models.Sequential([\n    layers.Input(shape=(32, 32, 3)),\n\n    layers.Conv2D(32, 3, padding='same', activation='relu'),\n    layers.Conv2D(32, 3, padding='same', activation='relu'),\n    layers.BatchNormalization(),\n    layers.MaxPooling2D(2),\n    layers.Dropout(0.2),\n\n    layers.Conv2D(64, 3, padding='same', activation='relu'),\n    layers.Conv2D(64, 3, padding='same', activation='relu'),\n    layers.BatchNormalization(),\n    layers.MaxPooling2D(2),\n    layers.Dropout(0.3),\n\n    layers.Conv2D(128, 3, padding='same', activation='relu'),\n    layers.Conv2D(128, 3, padding='same', activation='relu'),\n    layers.BatchNormalization(),\n    layers.MaxPooling2D(2),\n    layers.Dropout(0.4),\n\n    layers.Flatten(),\n    layers.Dense(256, activation='relu'),\n    layers.Dropout(0.5),\n    layers.Dense(10, activation='softmax')\n])\nmodel.summary()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import ReduceLROnPlateau\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\nreduce_lr = ReduceLROnPlateau(monitor='val_accuracy', factor=0.5, patience=5, min_lr=1e-6)\n\nhistory = model.fit(\n    datagen.flow(X_train, y_train_cat, batch_size=128),\n    epochs=80,\n    validation_data=(X_test, y_test_cat),\n    callbacks=[reduce_lr],\n    verbose=2\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_loss, test_acc = model.evaluate(X_test, y_test_cat, verbose=0)\nprint('Test accuracy:', test_acc)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\n\ndef find_file(filename):\n    matches = []\n    \n    for root, dirs, files in os.walk('/kaggle/input'):\n        if filename in files:\n            matches.append(os.path.join(root, filename))\n    \n    if not matches:\n        raise FileNotFoundError(f\"Could not find {filename}\")\n    \n    print(f\"{filename}: {matches[0]}\")\n    return matches[0]\n\nTRAIN_7Z = find_file(\"train.7z\")\nTEST_7Z = find_file(\"test.7z\")\nTRAIN_LABELS = find_file(\"trainLabels.csv\")\nSAMPLE_SUB = find_file(\"sampleSubmission.csv\")\n\nprint(\"\\nAll files found successfully!\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Load the sample submission to get the correct IDs\nsample_sub = pd.read_csv(SAMPLE_SUB)\n\n# Append '.png' to the IDs to match the extracted file names\nsample_sub['filename'] = sample_sub['id'].astype(str) + '.png'\n\n# Create a test generator to load the 300,000 Kaggle test images in batches\n# (Assumes the py7zr extraction placed images in '/kaggle/working/test')\ntest_datagen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=sample_sub,\n    directory='/kaggle/working/test', \n    x_col=\"filename\",\n    y_col=None,\n    target_size=(32, 32),\n    class_mode=None,\n    batch_size=128,\n    shuffle=False # Crucial: Keeps predictions in the exact order of sample_sub\n)\n\n# Generate predictions on the Kaggle test set\nprint(\"Generating predictions...\")\npredictions_prob = model.predict(test_generator, verbose=1)\npredictions_classes = np.argmax(predictions_prob, axis=1)\n\n# Map the numerical predictions back to the string class names\npredicted_labels = [CLASS_NAMES[i] for i in predictions_classes]\n\n# Format the final submission dataframe and save it\nsample_sub['label'] = predicted_labels\nsample_sub = sample_sub.drop(columns=['filename'])\nsample_sub.to_csv('/kaggle/working/submission.csv', index=False)\n\nprint(\"Saved submission.csv successfully!\")","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}