{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.10.12","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":30636,"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":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2024-01-22T20:40:26.272243Z","iopub.execute_input":"2024-01-22T20:40:26.272682Z","iopub.status.idle":"2024-01-22T20:40:26.281506Z","shell.execute_reply.started":"2024-01-22T20:40:26.272648Z","shell.execute_reply":"2024-01-22T20:40:26.280427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Import everything needed","metadata":{}},{"cell_type":"code","source":"import glob\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport collections\nimport math\nimport os\nimport shutil\nfrom sklearn.model_selection import train_test_split\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, Dataset\nimport torchvision\nfrom torchvision import datasets, transforms\nnp.random.seed(0)\ntorch.manual_seed(0)\ntorch.cuda.manual_seed(0)\n\nimport wandb\n#wandb.init(project='5_exercise_ML&DL', save_code=True)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:26:18.558893Z","iopub.execute_input":"2024-01-22T22:26:18.559608Z","iopub.status.idle":"2024-01-22T22:26:53.568992Z","shell.execute_reply.started":"2024-01-22T22:26:18.559570Z","shell.execute_reply":"2024-01-22T22:26:53.568130Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Unzip datasets","metadata":{}},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:41:12.360321Z","iopub.execute_input":"2024-01-22T20:41:12.360681Z","iopub.status.idle":"2024-01-22T20:41:25.040054Z","shell.execute_reply.started":"2024-01-22T20:41:12.360646Z","shell.execute_reply":"2024-01-22T20:41:25.039073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# WARNING: It can take a lot of time to uncompress!","metadata":{}},{"cell_type":"code","source":"!python -m py7zr x /kaggle/input/cifar-10/train.7z","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:41:25.041304Z","iopub.execute_input":"2024-01-22T20:41:25.041608Z","iopub.status.idle":"2024-01-22T20:42:23.732212Z","shell.execute_reply.started":"2024-01-22T20:41:25.041579Z","shell.execute_reply":"2024-01-22T20:42:23.731152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python -m py7zr x /kaggle/input/cifar-10/test.7z","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:42:23.735149Z","iopub.execute_input":"2024-01-22T20:42:23.735690Z","iopub.status.idle":"2024-01-22T21:01:08.237647Z","shell.execute_reply.started":"2024-01-22T20:42:23.735649Z","shell.execute_reply":"2024-01-22T21:01:08.236537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_dir = '/kaggle/working/'","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:26:56.403449Z","iopub.execute_input":"2024-01-22T22:26:56.403822Z","iopub.status.idle":"2024-01-22T22:26:56.873040Z","shell.execute_reply.started":"2024-01-22T22:26:56.403790Z","shell.execute_reply":"2024-01-22T22:26:56.872169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_csv_labels(fname):\n    \"\"\"Read `fname` to return a filename to label dictionary.\"\"\"\n    with open(fname, 'r') as f:\n        # Skip the file header line (column name)\n        lines = f.readlines()[1:]\n    tokens = [l.rstrip().split(',') for l in lines]\n    return dict(((name, label) for name, label in tokens))\n\nlabels = read_csv_labels(os.path.join(data_dir, '/kaggle/input/cifar-10/trainLabels.csv'))\nprint(f'Number training examples: {len(labels)}')\nprint(f'Number classes: {len(set(labels.values()))}')","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:26:58.341108Z","iopub.execute_input":"2024-01-22T22:26:58.341476Z","iopub.status.idle":"2024-01-22T22:26:58.866007Z","shell.execute_reply.started":"2024-01-22T22:26:58.341446Z","shell.execute_reply":"2024-01-22T22:26:58.865144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def copyfile(filename, target_dir):\n    \"\"\"Copy a file into a target directory.\"\"\"\n    os.makedirs(target_dir, exist_ok=True)\n    shutil.copy(filename, target_dir)\n\ndef reorg_train_valid(data_dir, labels, valid_ratio):\n    \"\"\"Split the validation set out of the original training set.\"\"\"\n    # The number of examples of the class that has the fewest examples in the\n    # training dataset\n    n = collections.Counter(labels.values()).most_common()[-1][1]\n    # The number of examples per class for the validation set\n    n_valid_per_label = max(1, math.floor(n * valid_ratio))\n    label_count = {}\n    for train_file in os.listdir(os.path.join(data_dir, 'train')):\n        label = labels[train_file.split('.')[0]]\n        fname = os.path.join(data_dir, 'train', train_file)\n        copyfile(fname, os.path.join(data_dir, 'train_valid_test',\n                                     'train_valid', label))\n        if label not in label_count or label_count[label] < n_valid_per_label:\n            copyfile(fname, os.path.join(data_dir, 'train_valid_test',\n                                         'valid', label))\n            label_count[label] = label_count.get(label, 0) + 1\n        else:\n            copyfile(fname, os.path.join(data_dir, 'train_valid_test',\n                                         'train', label))\n    return n_valid_per_label\n\ndef reorg_test(data_dir):\n    \"\"\"Organize the testing set for data loading during prediction.\"\"\"\n    for test_file in os.listdir(os.path.join(data_dir, 'test')):\n        copyfile(os.path.join(data_dir, 'test', test_file),\n                 os.path.join(data_dir, 'train_valid_test', 'test',\n                              'unknown'))\n        \ndef reorg_cifar10_data(data_dir, valid_ratio):\n    labels = read_csv_labels('/kaggle/input/cifar-10/trainLabels.csv')\n    reorg_train_valid(data_dir, labels, valid_ratio)\n    reorg_test(data_dir)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:27:01.619141Z","iopub.execute_input":"2024-01-22T22:27:01.619531Z","iopub.status.idle":"2024-01-22T22:27:02.163347Z","shell.execute_reply.started":"2024-01-22T22:27:01.619496Z","shell.execute_reply":"2024-01-22T22:27:02.162500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 64\nvalid_ratio = 0.1\nreorg_cifar10_data(data_dir, valid_ratio)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:27:04.279064Z","iopub.execute_input":"2024-01-22T22:27:04.279522Z","iopub.status.idle":"2024-01-22T22:28:07.091409Z","shell.execute_reply.started":"2024-01-22T22:27:04.279483Z","shell.execute_reply":"2024-01-22T22:28:07.090557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Transformations\n- Pre-trained networks usually apply some transformations to their inputs\n- TODOs:\n    - Check the transformations in the pre-trained ResNet and sync with yours! \n    - Consider adding more transformations, like HorizontalFlip, mnRandomSizeCrop","metadata":{}},{"cell_type":"code","source":"transform_train = torchvision.transforms.Compose([\n    torchvision.transforms.RandomHorizontalFlip(),\n    torchvision.transforms.RandomResizedCrop(32, scale=(0.8, 1.0), ratio=(0.8, 1.2)),\n    torchvision.transforms.ToTensor(),\n    torchvision.transforms.Normalize([0.4914, 0.4822, 0.4465],\n                                     [0.2023, 0.1994, 0.2010])\n])\n\ntransform_test = torchvision.transforms.Compose([\n    torchvision.transforms.ToTensor(),\n    torchvision.transforms.Normalize([0.4914, 0.4822, 0.4465],\n                                     [0.2023, 0.1994, 0.2010])])","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:28:49.986890Z","iopub.execute_input":"2024-01-22T22:28:49.987233Z","iopub.status.idle":"2024-01-22T22:28:50.457634Z","shell.execute_reply.started":"2024-01-22T22:28:49.987206Z","shell.execute_reply":"2024-01-22T22:28:50.456693Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ds, train_valid_ds = [torchvision.datasets.ImageFolder(\n    os.path.join(data_dir, 'train_valid_test', folder),\n    transform=transform_train) for folder in ['train', 'train_valid']]\n\nvalid_ds, test_ds = [torchvision.datasets.ImageFolder(\n    os.path.join(data_dir, 'train_valid_test', folder),\n    transform=transform_test) for folder in ['valid', 'test']]\n\ntrain_iter, train_valid_iter = [torch.utils.data.DataLoader(\n    dataset, batch_size, shuffle=True, drop_last=True)\n    for dataset in (train_ds, train_valid_ds)]\n\nvalid_iter = torch.utils.data.DataLoader(valid_ds, batch_size, shuffle=False,\n                                         drop_last=True)\n\ntest_iter = torch.utils.data.DataLoader(test_ds, batch_size, shuffle=False,\n                                        drop_last=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:28:54.460725Z","iopub.execute_input":"2024-01-22T22:28:54.461116Z","iopub.status.idle":"2024-01-22T22:28:56.895950Z","shell.execute_reply.started":"2024-01-22T22:28:54.461083Z","shell.execute_reply":"2024-01-22T22:28:56.895078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## TODO: \n* Define the data augmentation technique \n* Fine-tune a pre-trained ResNet-18 on CIFAR-10\n* Submit your submission file to Kaggle (as described in the competition rules) and get your accuracy on the test set","metadata":{}},{"cell_type":"code","source":"model = torchvision.models.resnet18(pretrained=True)\n\nnum_classes = 10\nmodel.fc = nn.Linear(model.fc.in_features, num_classes)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\nscheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)\n\ndef train_epoch(model, train_loader, criterion, optimizer, device):\n    model.train()\n    total_loss = 0.0\n    for inputs, labels in train_loader:\n        inputs, labels = inputs.to(device), labels.to(device)\n        optimizer.zero_grad()\n        outputs = model(inputs)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n        total_loss += loss.item()\n    return total_loss / len(train_loader)\n\ndef validate(model, val_loader, criterion, device):\n    model.eval()\n    total_loss = 0.0\n    correct = 0\n    total_samples = 0\n    with torch.no_grad():\n        for inputs, labels in val_loader:\n            inputs, labels = inputs.to(device), labels.to(device)\n            outputs = model(inputs)\n            loss = criterion(outputs, labels)\n            total_loss += loss.item()\n            _, predicted = torch.max(outputs, 1)\n            correct += (predicted == labels).sum().item()\n            total_samples += labels.size(0)\n    return total_loss / len(val_loader), correct / total_samples\n\n\nnum_epochs = 50\nfor epoch in range(num_epochs):\n    train_loss = train_epoch(model, train_iter, criterion, optimizer, device)\n    val_loss, val_accuracy = validate(model, valid_iter, criterion, device)\n    scheduler.step()\n\n    print(f\"Epoch {epoch + 1}/{num_epochs} => \"\n          f\"Train Loss: {train_loss:.4f}, \"\n          f\"Validation Loss: {val_loss:.4f}, \"\n          f\"Validation Accuracy: {val_accuracy * 100:.2f}%\")\n    #wandb.log({\"epoch\": epoch, \"train_loss\": train_loss, \"val_loss\": val_loss, \"val_accuracy\": (val_accuracy * 100)})\n\nmodel.eval()\ntest_predictions = []\nwith torch.no_grad():\n    for inputs, _ in test_iter:\n        inputs = inputs.to(device)\n        outputs = model(inputs)\n        _, predicted = torch.max(outputs, 1)\n        test_predictions.extend(predicted.cpu().numpy())","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:28:59.503463Z","iopub.execute_input":"2024-01-22T22:28:59.503821Z","iopub.status.idle":"2024-01-22T23:07:10.829203Z","shell.execute_reply.started":"2024-01-22T22:28:59.503785Z","shell.execute_reply":"2024-01-22T23:07:10.828288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_filenames = [os.path.splitext(os.path.basename(str(fname)))[0] for fname in test_ds.imgs]\nsubmission_df = pd.DataFrame({\n    'id': test_filenames,\n    'label': [train_ds.classes[p] for p in test_predictions]\n})\n\nsubmission_df.to_csv('/kaggle/working/submission.csv', index=False)\nprint(\"Submission file created successfully.\")","metadata":{"execution":{"iopub.status.busy":"2024-01-22T21:41:17.771821Z","iopub.execute_input":"2024-01-22T21:41:17.772109Z","iopub.status.idle":"2024-01-22T21:41:20.460216Z","shell.execute_reply.started":"2024-01-22T21:41:17.772082Z","shell.execute_reply":"2024-01-22T21:41:20.459323Z"},"trusted":true},"execution_count":null,"outputs":[]}]}