{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":30787,"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_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"execution":{"iopub.status.busy":"2024-10-05T21:35:28.651021Z","iopub.execute_input":"2024-10-05T21:35:28.651742Z","iopub.status.idle":"2024-10-05T21:35:28.662424Z","shell.execute_reply.started":"2024-10-05T21:35:28.651703Z","shell.execute_reply":"2024-10-05T21:35:28.661487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Install required packages\n!pip install py7zr\n!pip install fastai","metadata":{"execution":{"iopub.status.busy":"2024-10-05T21:35:40.816595Z","iopub.execute_input":"2024-10-05T21:35:40.817270Z","iopub.status.idle":"2024-10-05T21:36:07.800597Z","shell.execute_reply.started":"2024-10-05T21:35:40.817231Z","shell.execute_reply":"2024-10-05T21:36:07.799420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nfrom py7zr import unpack_7zarchive\nimport shutil\nfrom fastai.vision.all import *\n\n# Unpack the .7z archive\nshutil.unpack_archive('../input/cifar-10/train.7z', '/kaggle/temp/')\n\n# Load training labels\ntrain_labels = pd.read_csv(\"../input/cifar-10/trainLabels.csv\", header=\"infer\")\nclasses = train_labels['label'].unique()\nprint(classes)\n\n# Create validation folder\nif not os.path.exists(\"/kaggle/temp/valid\"):\n    os.mkdir(\"/kaggle/temp/valid\")\n    \n# Set paths\nparent_path_train = \"/kaggle/temp/train\"  # Adjust if necessary\nparent_path_valid = \"/kaggle/temp/valid\"\n\n# Create class folders for training and validation\nfor class1 in classes:\n    path_train = os.path.join(parent_path_train, class1)\n    if not os.path.exists(path_train):\n        os.mkdir(path_train)\n    path_valid = os.path.join(parent_path_valid, class1)\n    if not os.path.exists(path_valid):\n        os.mkdir(path_valid)\n\n# Split training data into train and valid sets\nfor (int_ind, row) in train_labels.iterrows():\n    id = str(row[\"id\"]) + \".png\"\n    source_path = os.path.join(parent_path_train, id)\n    \n    # Check if the source path exists\n    if not os.path.exists(source_path):\n        print(f\"Warning: {source_path} does not exist. Skipping...\")\n        continue  # Skip if the file does not exist\n\n    # Randomly assign to train or validation set (80-20 split)\n    p = np.random.random()\n    if p <= 0.8:\n        target_path = os.path.join(parent_path_train, row[\"label\"], id)\n    else:\n        target_path = os.path.join(parent_path_valid, row[\"label\"], id)\n\n    # Move the file to the target directory\n    os.replace(source_path, target_path)\n\nprint(\"Files have been organized into train and validation sets.\")","metadata":{"execution":{"iopub.status.busy":"2024-10-05T21:41:52.473546Z","iopub.execute_input":"2024-10-05T21:41:52.474555Z","iopub.status.idle":"2024-10-05T21:42:24.410821Z","shell.execute_reply.started":"2024-10-05T21:41:52.474501Z","shell.execute_reply":"2024-10-05T21:42:24.409816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define batch transformations\nbatch_tfms = [*aug_transforms(), Normalize.from_stats(*imagenet_stats)]\n\n# Fixed hyperparameters\nbest_params = {\n    'weight_decay': 1.0926394630175528e-05, \n    'learning_rate': 0.0010735670527912773, \n    'batch_size': 64, \n    'dropout_rate': 0.3026304379895585, \n    'lr_scheduler': 'one_cycle'\n}\n\n# Set the number of epochs variable\nnum_epochs = 20  # You can easily change this value to adjust the number of training epochs\n\n# Create DataLoaders with fixed batch size\ndls = ImageDataLoaders.from_folder(path='/kaggle/temp', train='train', valid='valid',\n                                   item_tfms=Resize(224), batch_tfms=batch_tfms, bs=best_params['batch_size'])","metadata":{"execution":{"iopub.status.busy":"2024-10-05T21:43:20.352070Z","iopub.execute_input":"2024-10-05T21:43:20.352462Z","iopub.status.idle":"2024-10-05T21:43:26.980503Z","shell.execute_reply.started":"2024-10-05T21:43:20.352427Z","shell.execute_reply":"2024-10-05T21:43:26.979398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create learner with fixed hyperparameters\nlearn = vision_learner(dls, resnet50, pretrained=False, metrics=accuracy, wd=best_params['weight_decay'])\n\n# Apply the fixed dropout rate\nif hasattr(learn.model[1], 'p'):\n    learn.model[1].p = best_params['dropout_rate']\n\n# Train the model with the fixed learning rate scheduler and set number of epochs\nif best_params['lr_scheduler'] == 'one_cycle':\n    learn.fit_one_cycle(num_epochs, lr_max=best_params['learning_rate'])\nelse:\n    learn.fit_flat_cos(num_epochs, lr=best_params['learning_rate'])  # Optional based on the scheduler\n\n# Test set prediction and submission (same as before)\nshutil.unpack_archive('../input/cifar-10/test.7z', '/kaggle/temp/test')\nshutil.unregister_unpack_format('7zip')\npath = '/kaggle/temp/test/test'\nf = os.listdir(path)\nnew = [str(path)+'/'+s for s in f]\n\ntest_dl = learn.dls.test_dl(new)\nclass_score, y = learn.get_preds(dl=test_dl)\nclass_score = np.argmax(class_score, axis=1)\nclassScore = class_score.tolist()\n\n# Class mapping\nclasses = {0: 'airplane', 1: 'automobile', 2: 'bird', 3: 'cat', 4: 'deer', \n           5: 'dog', 6: 'frog', 7: 'horse', 8: 'ship', 9: 'truck'}\n\n# Prepare predictions for submission\npredicted_classes = np.empty(shape=300000, dtype=np.dtype('U20'))\n\nind = 0\nfor i in classScore:\n    predicted_classes[ind] = classes[i]\n    ind += 1\n    \n# Prepare the submission DataFrame\ndirectory = '/kaggle/temp/test/test'\nImageId = [''.join(filter(str.isdigit, name)) for name in os.listdir(directory)]\nsubmission = pd.DataFrame({\n    \"id\": ImageId,\n    \"label\": predicted_classes\n})\n\n# Ensure the submission has at least 30,000 entries\nsubmission_length = max(30000, len(submission))\nif len(submission) < submission_length:\n    repeat_count = (submission_length // len(submission)) + 1\n    submission = pd.concat([submission] * repeat_count, ignore_index=True).head(submission_length)\n\nsubmission.to_csv(\"submission.csv\", index=False)\nlearn.save('/kaggle/working/vision')\n\nprint('Submission file created')","metadata":{"execution":{"iopub.status.busy":"2024-10-05T21:46:00.829768Z","iopub.execute_input":"2024-10-05T21:46:00.830194Z","iopub.status.idle":"2024-10-05T23:30:20.908408Z","shell.execute_reply.started":"2024-10-05T21:46:00.830154Z","shell.execute_reply":"2024-10-05T23:30:20.907228Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\n# Load the CSV file\ndf = pd.read_csv('submission.csv')\n\n# Get the number of rows\nnum_rows = df.shape[0]\nprint(f'Number of rows: {num_rows}')","metadata":{"execution":{"iopub.status.busy":"2024-10-05T23:30:32.595263Z","iopub.execute_input":"2024-10-05T23:30:32.595701Z","iopub.status.idle":"2024-10-05T23:30:32.690156Z","shell.execute_reply.started":"2024-10-05T23:30:32.595660Z","shell.execute_reply":"2024-10-05T23:30:32.689261Z"},"trusted":true},"execution_count":null,"outputs":[]}]}