{"metadata":{"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":30787,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.14"},"papermill":{"default_parameters":{},"duration":5229.900508,"end_time":"2024-10-02T20:54:27.010094","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-10-02T19:27:17.109586","version":"2.6.0"}},"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":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":0.776311,"end_time":"2024-10-02T19:27:20.699451","exception":false,"start_time":"2024-10-02T19:27:19.923140","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-10-05T14:52:38.723300Z","iopub.execute_input":"2024-10-05T14:52:38.723608Z","iopub.status.idle":"2024-10-05T14:52:39.787644Z","shell.execute_reply.started":"2024-10-05T14:52:38.723575Z","shell.execute_reply":"2024-10-05T14:52:39.786480Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Install required packages\n!pip install py7zr\n!pip install fastai\n\n# Required imports\nimport 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 dataset\nshutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)\nshutil.unpack_archive('../input/cifar-10/train.7z', '/kaggle/temp/')\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\"\nparent_path_valid = \"/kaggle/temp/valid\"\n\n# Create class folders\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    # 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        os.replace(source_path, target_path)\n    else:\n        target_path = os.path.join(parent_path_valid, row[\"label\"], id)\n        os.replace(source_path, target_path)\n\n# 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'])\n\n# 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]\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 with at least 30,000 rows.')\n","metadata":{"papermill":{"duration":5223.677449,"end_time":"2024-10-02T20:54:24.379035","exception":false,"start_time":"2024-10-02T19:27:20.701586","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-10-05T14:52:39.789283Z","iopub.execute_input":"2024-10-05T14:52:39.789714Z","iopub.status.idle":"2024-10-05T16:20:11.125926Z","shell.execute_reply.started":"2024-10-05T14:52:39.789678Z","shell.execute_reply":"2024-10-05T16:20:11.124830Z"},"trusted":true},"execution_count":null,"outputs":[]}]}