{"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":30775,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install py7zr","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Required imports\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    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 = {'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# 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('/kaggle/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\nlearn.dls.vocab\nclasses = {0: 'airplane', 1: 'automobile', 2: 'bird', 3: 'cat', 4: 'deer', 5: 'dog', 6: 'frog', 7: 'horse', 8: 'ship', 9: 'truck'}\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\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\nsubmission.to_csv(\"submission.csv\", index=False)\nlearn.save('/kaggle/working/vision')\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-09-29T06:44:12.822084Z","iopub.execute_input":"2024-09-29T06:44:12.822510Z","iopub.status.idle":"2024-09-29T06:44:25.551336Z","shell.execute_reply.started":"2024-09-29T06:44:12.822467Z","shell.execute_reply":"2024-09-29T06:44:25.549341Z"},"trusted":true},"execution_count":null,"outputs":[]}]}