{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","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":30733,"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","execution":{"iopub.status.busy":"2024-06-06T20:49:56.656084Z","iopub.execute_input":"2024-06-06T20:49:56.656435Z","iopub.status.idle":"2024-06-06T20:49:58.679108Z","shell.execute_reply.started":"2024-06-06T20:49:56.656403Z","shell.execute_reply":"2024-06-06T20:49:58.678029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Input, Conv2D, Dense, Flatten, Dropout\nfrom tensorflow.keras.layers import GlobalMaxPooling2D, MaxPooling2D\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.models import Model\nfrom keras.callbacks import EarlyStopping\nfrom tensorflow.keras import regularizers, optimizers\nfrom tensorflow.keras import datasets, layers, models\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.metrics import accuracy_score\nfrom PIL import ImageFont\nimport warnings \nwarnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2024-06-06T20:49:58.680983Z","iopub.execute_input":"2024-06-06T20:49:58.681368Z","iopub.status.idle":"2024-06-06T20:50:18.383490Z","shell.execute_reply.started":"2024-06-06T20:49:58.681340Z","shell.execute_reply":"2024-06-06T20:50:18.382629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Importing the CIFAR-10 dataset from Keras \nfrom tensorflow.keras.datasets import cifar10\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()","metadata":{"execution":{"iopub.status.busy":"2024-06-06T20:50:18.388665Z","iopub.execute_input":"2024-06-06T20:50:18.388946Z","iopub.status.idle":"2024-06-06T20:50:23.145738Z","shell.execute_reply.started":"2024-06-06T20:50:18.388921Z","shell.execute_reply":"2024-06-06T20:50:23.144905Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-06T20:50:23.146790Z","iopub.execute_input":"2024-06-06T20:50:23.147091Z","iopub.status.idle":"2024-06-06T20:50:23.152860Z","shell.execute_reply.started":"2024-06-06T20:50:23.147066Z","shell.execute_reply":"2024-06-06T20:50:23.151918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Normalizing\nX_train = X_train/255\nX_test = X_test/255\n\n# One-Hot-Encoding\ny_train_en = to_categorical(y_train,10)\ny_test_en = to_categorical(y_test,10)","metadata":{"execution":{"iopub.status.busy":"2024-06-06T20:50:23.154002Z","iopub.execute_input":"2024-06-06T20:50:23.154289Z","iopub.status.idle":"2024-06-06T20:50:23.637898Z","shell.execute_reply.started":"2024-06-06T20:50:23.154263Z","shell.execute_reply":"2024-06-06T20:50:23.636992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n               'dog', 'frog', 'horse', 'ship', 'truck']\n\nplt.figure(figsize=(10,6))\nfor i in range(16):\n    plt.subplot(4,4,i+1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    plt.imshow(X_train[i])\n    # The CIFAR labels happen to be arrays, \n    # which is why you need the extra index\n    plt.xlabel(class_names[y_train[i][0]])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-06T20:50:23.638955Z","iopub.execute_input":"2024-06-06T20:50:23.639238Z","iopub.status.idle":"2024-06-06T20:50:24.391388Z","shell.execute_reply.started":"2024-06-06T20:50:23.639215Z","shell.execute_reply":"2024-06-06T20:50:24.390415Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Model_3 with Batch Normalization\nmodel = Sequential()\nmodel.add(Conv2D(264,(4,4),input_shape=(32,32,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128,(4,4),input_shape=(32,32,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(512,(4,4),input_shape=(32,32,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128,(4,4),input_shape=(32,32,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(128,(4,4),input_shape=(32,32,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128,(4,4),input_shape=(32,32,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.35))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-06-06T20:50:24.392526Z","iopub.execute_input":"2024-06-06T20:50:24.392817Z","iopub.status.idle":"2024-06-06T20:50:25.853993Z","shell.execute_reply.started":"2024-06-06T20:50:24.392791Z","shell.execute_reply":"2024-06-06T20:50:25.853186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define early stopping callback\nearly_stopping = EarlyStopping(monitor='val_loss', patience=10)\n\n# Fit the model with early stopping\nhistory = model.fit(X_train, y_train_en, epochs=100, verbose=1, \n                    validation_data=(X_test, y_test_en), callbacks=[early_stopping])\n","metadata":{"execution":{"iopub.status.busy":"2024-06-06T20:50:25.855143Z","iopub.execute_input":"2024-06-06T20:50:25.855520Z","iopub.status.idle":"2024-06-06T21:23:55.975422Z","shell.execute_reply.started":"2024-06-06T20:50:25.855486Z","shell.execute_reply":"2024-06-06T21:23:55.974323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import py7zr\nfrom PIL import Image\nimport os\n\n# Ensure the file paths are correct and point to valid 7z files\ntrain_seven_zip_file_path = '/kaggle/input/cifar-10/train.7z'\ntest_seven_zip_file_path = '/kaggle/input/cifar-10/test.7z'\n\n# List to store the images for train and test sets\ntrain_images = []\ntest_images = []\n\n# List to store the Image IDs\ntest_image_ids = []\n\n# Helper function to recursively find image files\ndef find_images(directory):\n    image_files = []\n    for root, _, files in os.walk(directory):\n        for file in files:\n            if file.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):\n                image_files.append(os.path.join(root, file))\n    return image_files\n\n# Extract the 7z files and read the images for train set\ntry:\n    with py7zr.SevenZipFile(train_seven_zip_file_path, mode='r') as z:\n        z.extractall(path='train_extracted_files')\n    \n    # Find all image files in the extracted directory\n    train_image_files = find_images('train_extracted_files')\n    \n    # Iterate through the image files and load them into the list\n    for image_file_path in train_image_files:\n        img = Image.open(image_file_path)\n        train_images.append(img)\n    \n    # Check the number of images loaded for train set\n    print(f\"Loaded {len(train_images)} images for train set.\")\n\nexcept Exception as e:\n    print(f\"An error occurred during train set processing: {e}\")\n\n# Extract the 7z files and read the images for test set\ntry:\n    with py7zr.SevenZipFile(test_seven_zip_file_path, mode='r') as z:\n        z.extractall(path='test_extracted_files')\n    \n    # Find all image files in the extracted directory\n    test_image_files = find_images('test_extracted_files')\n    \n    # Iterate through the image files and load them into the list\n    for image_file_path in test_image_files:\n        img = Image.open(image_file_path)\n        test_images.append(img)\n        \n        # Extract Image ID from the filename and append to the list\n        image_id = int(''.join(filter(str.isdigit, os.path.basename(image_file_path))))\n        test_image_ids.append(image_id)\n    \n    # Check the number of images loaded for test set\n    print(f\"Loaded {len(test_images)} images for test set.\")\n\nexcept Exception as e:\n    print(f\"An error occurred during test set processing: {e}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-06-06T21:32:30.447621Z","iopub.execute_input":"2024-06-06T21:32:30.448339Z","iopub.status.idle":"2024-06-06T21:36:51.810307Z","shell.execute_reply.started":"2024-06-06T21:32:30.448304Z","shell.execute_reply":"2024-06-06T21:36:51.809141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\n\n# Dictionary mapping numerical labels to class names\nclass_names = {\n    0: 'airplane',\n    1: 'automobile',\n    2: 'bird',\n    3: 'cat',\n    4: 'deer',\n    5: 'dog',\n    6: 'frog',\n    7: 'horse',\n    8: 'ship',\n    9: 'truck'\n}\n\n# Convert test images to arrays\ntest_image_arrays = [np.array(img) for img in test_images]\n\n# Stack the test images into a 4D NumPy array\ntest_images_array = np.stack(test_image_arrays)\n\n# Predict labels for the test set\npredictions = model.predict(test_images_array)\n\n# Convert numerical labels to class names\npredicted_class_names = [class_names[np.argmax(label)] for label in predictions]\n\n# Create a DataFrame with 'id' and 'label' (class names)\nsubmission = pd.DataFrame({\n    'id': test_image_ids,\n    'label': predicted_class_names\n})\n\n# Check if the DataFrame is empty\nif submission.empty:\n    print(\"DataFrame is empty. Check your predictions.\")\nelse:\n    # Save the DataFrame to a CSV file\n    submission.to_csv('/kaggle/working/submission.csv', index=False)\n    print(\"Predictions saved to submission.csv.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-06-06T21:37:57.021091Z","iopub.execute_input":"2024-06-06T21:37:57.021670Z","iopub.status.idle":"2024-06-06T21:41:22.585023Z","shell.execute_reply.started":"2024-06-06T21:37:57.021638Z","shell.execute_reply":"2024-06-06T21:41:22.583916Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.head(20)","metadata":{"execution":{"iopub.status.busy":"2024-06-06T21:42:08.740548Z","iopub.execute_input":"2024-06-06T21:42:08.741464Z","iopub.status.idle":"2024-06-06T21:42:08.752937Z","shell.execute_reply.started":"2024-06-06T21:42:08.741429Z","shell.execute_reply":"2024-06-06T21:42:08.751890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}