{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.11.13","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":31193,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true},"papermill":{"default_parameters":{},"duration":32570.753494,"end_time":"2024-10-12T09:04:29.685846","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-10-12T00:01:38.932352","version":"2.6.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"id":"f1332d9c","cell_type":"code","source":"!pip install py7zr","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2025-12-02T02:34:38.144290Z","iopub.execute_input":"2025-12-02T02:34:38.144659Z","iopub.status.idle":"2025-12-02T02:34:43.832383Z","shell.execute_reply.started":"2025-12-02T02:34:38.144635Z","shell.execute_reply":"2025-12-02T02:34:43.831682Z"},"papermill":{"duration":15.152559,"end_time":"2024-10-12T00:01:56.838428","exception":false,"start_time":"2024-10-12T00:01:41.685869","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"id":"2cca76d9-53cd-4cc9-b19f-332f70cdb013","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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T02:34:43.833812Z","iopub.execute_input":"2025-12-02T02:34:43.834036Z","iopub.status.idle":"2025-12-02T02:34:56.465002Z","shell.execute_reply.started":"2025-12-02T02:34:43.834014Z","shell.execute_reply":"2025-12-02T02:34:56.464424Z"}},"outputs":[],"execution_count":null},{"id":"16b2cef6-e732-4839-89f5-174a255b1d45","cell_type":"code","source":"# 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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T02:34:56.465746Z","iopub.execute_input":"2025-12-02T02:34:56.466013Z","iopub.status.idle":"2025-12-02T02:34:56.473311Z","shell.execute_reply.started":"2025-12-02T02:34:56.465985Z","shell.execute_reply":"2025-12-02T02:34:56.472592Z"}},"outputs":[],"execution_count":null},{"id":"7c10fa69-459a-4eba-9880-c03efa316b66","cell_type":"code","source":"# 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)]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T02:34:56.474931Z","iopub.execute_input":"2025-12-02T02:34:56.475126Z","iopub.status.idle":"2025-12-02T02:35:21.687435Z","shell.execute_reply.started":"2025-12-02T02:34:56.475110Z","shell.execute_reply":"2025-12-02T02:35:21.686646Z"}},"outputs":[],"execution_count":null},{"id":"372bd21f-16bb-49d5-8f73-9c2274cd9ce7","cell_type":"code","source":"# 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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-02T02:35:21.688297Z","iopub.execute_input":"2025-12-02T02:35:21.688579Z","iopub.status.idle":"2025-12-02T11:04:41.158659Z","shell.execute_reply.started":"2025-12-02T02:35:21.688553Z","shell.execute_reply":"2025-12-02T11:04:41.157751Z"}},"outputs":[],"execution_count":null},{"id":"2c492d9e","cell_type":"code","source":"# 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":{"execution":{"iopub.status.busy":"2025-12-02T11:04:41.159916Z","iopub.execute_input":"2025-12-02T11:04:41.160177Z","iopub.status.idle":"2025-12-02T11:16:35.069025Z","shell.execute_reply.started":"2025-12-02T11:04:41.160157Z","shell.execute_reply":"2025-12-02T11:16:35.068317Z"},"papermill":{"duration":32549.529248,"end_time":"2024-10-12T09:04:26.371611","exception":false,"start_time":"2024-10-12T00:01:56.842363","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null}]}