{"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":30776,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install py7zr","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-10-05T16:51:48.409685Z","iopub.execute_input":"2024-10-05T16:51:48.410561Z","iopub.status.idle":"2024-10-05T16:52:05.485685Z","shell.execute_reply.started":"2024-10-05T16:51:48.410513Z","shell.execute_reply":"2024-10-05T16:52:05.484369Z"},"trusted":true},"outputs":[],"execution_count":null},{"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 *\nfrom functools import partial\n\n# Define CutOut transformation manually\nclass CutOut(RandTransform):\n    def __init__(self, n_holes=1, length=20, **kwargs):\n        super().__init__(**kwargs)\n        self.n_holes, self.length = n_holes, length\n        \n    def encodes(self, img:TensorImage):\n        h, w = img.shape[-2:]\n        mask = torch.ones((h, w), device=img.device)\n        for _ in range(self.n_holes):\n            y = np.random.randint(h)\n            x = np.random.randint(w)\n\n            y1 = np.clip(y - self.length // 2, 0, h)\n            y2 = np.clip(y + self.length // 2, 0, h)\n            x1 = np.clip(x - self.length // 2, 0, w)\n            x2 = np.clip(x + self.length // 2, 0, w)\n\n            mask[y1: y2, x1: x2] = 0.\n\n        return img * mask.unsqueeze(0)\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 advanced data augmentation methods including CutOut\nbatch_tfms = [*aug_transforms(), Normalize.from_stats(*imagenet_stats), CutOut(n_holes=1, length=20)]\n\n# Fixed hyperparameters\nbest_params = {'weight_decay': 3.1595250466032746e-05,\n               'learning_rate': 0.0007394699205144519,\n               'batch_size': 16, \n               'dropout_rate': 0.10845782679503657}\n\n\nnum_epochs = 100  # Set the number of epochs variable\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# Define AdamW using partial\nadamw_opt = partial(Adam, wd=best_params['weight_decay'])\n\n# Create learner with resnet50 with randomly initialized weights and advanced optimizer AdamW\nlearn = vision_learner(dls, resnet50, pretrained=False, metrics=accuracy, wd=best_params['weight_decay'], opt_func=adamw_opt)\n\n# Apply the fixed dropout rate\nif hasattr(learn.model[1], 'p'):\n    learn.model[1].p = best_params['dropout_rate']\n\n# Manually implement warmup + cosine annealing\ndef cosine_warmup_schedule(learn, warmup_epochs=5, max_lr=best_params['learning_rate'], num_epochs=num_epochs):\n    # Warmup phase\n    for epoch in range(warmup_epochs):\n        warmup_lr = max_lr * (epoch + 1) / warmup_epochs\n        print(f\"Epoch {epoch + 1}/{num_epochs}: Warmup with LR = {warmup_lr}\")\n        learn.fit_one_cycle(1, lr_max=warmup_lr)\n    \n    # Cosine annealing phase\n    learn.fit_flat_cos(num_epochs - warmup_epochs, lr=max_lr)\n\n# Train the model using cosine annealing with manual warmup\ncosine_warmup_schedule(learn)\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')","metadata":{},"outputs":[],"execution_count":null}]}