{"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":"markdown","source":"### Kaggle Notebook Link: https://www.kaggle.com/code/leventeszabo1/ml-dl-cifar-10\n### W&B Link: https://wandb.ai/work-levente/cifar10_resnet18","metadata":{}},{"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))\nprint(\"Contents of /kaggle/working/:\")\nfor dirname, _, filenames in os.walk('/kaggle/working'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\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-22T21:47:27.550359Z","iopub.execute_input":"2024-01-22T21:47:27.550817Z","iopub.status.idle":"2024-01-22T21:47:28.087149Z","shell.execute_reply.started":"2024-01-22T21:47:27.550779Z","shell.execute_reply":"2024-01-22T21:47:28.084447Z"},"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\nimport wandb\nnp.random.seed(0)\ntorch.manual_seed(0)\ntorch.cuda.manual_seed(0)\n\nwandb.init(project='cifar10_resnet18')","metadata":{"execution":{"iopub.status.busy":"2024-01-22T21:47:28.089587Z","iopub.execute_input":"2024-01-22T21:47:28.090179Z","iopub.status.idle":"2024-01-22T21:48:27.163412Z","shell.execute_reply.started":"2024-01-22T21:47:28.090140Z","shell.execute_reply":"2024-01-22T21:48:27.162400Z"},"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-22T21:48:27.164900Z","iopub.execute_input":"2024-01-22T21:48:27.167425Z","iopub.status.idle":"2024-01-22T21:48:45.310871Z","shell.execute_reply.started":"2024-01-22T21:48:27.167381Z","shell.execute_reply":"2024-01-22T21:48:45.309687Z"},"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-22T21:48:45.312582Z","iopub.execute_input":"2024-01-22T21:48:45.315189Z","iopub.status.idle":"2024-01-22T21:49:50.691084Z","shell.execute_reply.started":"2024-01-22T21:48:45.315142Z","shell.execute_reply":"2024-01-22T21:49:50.689528Z"},"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-22T21:49:50.696013Z","iopub.execute_input":"2024-01-22T21:49:50.697568Z","iopub.status.idle":"2024-01-22T22:12:12.265065Z","shell.execute_reply.started":"2024-01-22T21:49:50.697529Z","shell.execute_reply":"2024-01-22T22:12:12.263358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_dir = '/kaggle/working/'","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:12:12.266643Z","iopub.execute_input":"2024-01-22T22:12:12.266976Z","iopub.status.idle":"2024-01-22T22:12:12.274607Z","shell.execute_reply.started":"2024-01-22T22:12:12.266943Z","shell.execute_reply":"2024-01-22T22:12:12.273364Z"},"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:12:12.276280Z","iopub.execute_input":"2024-01-22T22:12:12.276751Z","iopub.status.idle":"2024-01-22T22:12:12.385356Z","shell.execute_reply.started":"2024-01-22T22:12:12.276712Z","shell.execute_reply":"2024-01-22T22:12:12.384161Z"},"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:12:12.387111Z","iopub.execute_input":"2024-01-22T22:12:12.387542Z","iopub.status.idle":"2024-01-22T22:12:12.402641Z","shell.execute_reply.started":"2024-01-22T22:12:12.387504Z","shell.execute_reply":"2024-01-22T22:12:12.401562Z"},"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:12:12.403994Z","iopub.execute_input":"2024-01-22T22:12:12.404622Z","iopub.status.idle":"2024-01-22T22:13:22.109219Z","shell.execute_reply.started":"2024-01-22T22:12:12.404583Z","shell.execute_reply":"2024-01-22T22:13:22.107707Z"},"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":"# Define transformations for training data\ntransform_train = torchvision.transforms.Compose([\n    torchvision.transforms.RandomResizedCrop(224),     # Randomly resize and crop the image to 224x224\n    torchvision.transforms.RandomHorizontalFlip(),     # Randomly flip the image horizontally\n    torchvision.transforms.ToTensor(),\n    torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])  # Normalize with ImageNet stats\n])\n\n# Define transformations for test data (no random transformations here)\ntransform_test = torchvision.transforms.Compose([\n    torchvision.transforms.Resize(256),\n    torchvision.transforms.CenterCrop(224),\n    torchvision.transforms.ToTensor(),\n    torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:13:22.111131Z","iopub.execute_input":"2024-01-22T22:13:22.111956Z","iopub.status.idle":"2024-01-22T22:13:22.125054Z","shell.execute_reply.started":"2024-01-22T22:13:22.111905Z","shell.execute_reply":"2024-01-22T22:13:22.123368Z"},"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:13:22.126919Z","iopub.execute_input":"2024-01-22T22:13:22.127263Z","iopub.status.idle":"2024-01-22T22:13:24.597254Z","shell.execute_reply.started":"2024-01-22T22:13:22.127232Z","shell.execute_reply":"2024-01-22T22:13:24.595855Z"},"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":"# Check if GPU is available and set the device accordingly\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(\"Using device:\", device)\n\n# Load pre-trained ResNet-18 model\nresnet18 = torchvision.models.resnet18(pretrained=True)\nresnet18.fc = nn.Linear(resnet18.fc.in_features, 10)  # Adjust for CIFAR-10\n\n# Move the model to GPU if available\nresnet18 = resnet18.to(device)\n\n\n# Set up loss function and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(resnet18.parameters(), lr=0.001, momentum=0.9)\nscheduler = optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)\n\n# Training loop (simplified version)\nnum_epochs = 10  # Set the number of epochs\nfor epoch in range(num_epochs):\n    resnet18.train()  # Set model to training mode\n    running_loss = 0.0\n    for inputs, labels in train_iter:\n        inputs, labels = inputs.to(device), labels.to(device)\n        optimizer.zero_grad()\n        outputs = resnet18(inputs)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n        running_loss += loss.item()\n    scheduler.step()\n    print(f'Epoch {epoch+1}/{num_epochs}, Loss: {running_loss/len(train_iter)}')\n    wandb.log({\"epoch_loss\": running_loss/len(train_iter)})\n","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:13:24.598760Z","iopub.execute_input":"2024-01-22T22:13:24.599149Z","iopub.status.idle":"2024-01-22T22:41:04.547446Z","shell.execute_reply.started":"2024-01-22T22:13:24.599086Z","shell.execute_reply":"2024-01-22T22:41:04.545358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"resnet18.eval()  # Set model to evaluation mode\nall_preds = []\nwith torch.no_grad():\n    for inputs, _ in \n    :\n        # Move the inputs to the same device as the model (GPU, if available)\n        inputs = inputs.to(device)\n\n        outputs = resnet18(inputs)\n        _, preds = torch.max(outputs, 1)\n        all_preds.extend(preds.cpu().numpy())\n\n# Create a submission file\nsubmission = pd.DataFrame({'id': range(1, len(all_preds) + 1), 'label': all_preds})\nlabel_map = {0: 'airplane', 1: 'automobile', 2: 'bird', 3: 'cat', 4: 'deer',\n             5: 'dog', 6: 'frog', 7: 'horse', 8: 'ship', 9: 'truck'}\nsubmission['label'] = submission['label'].map(label_map)\n\nsubmission.to_csv('submission.csv', index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-01-22T23:05:47.475997Z","iopub.execute_input":"2024-01-22T23:05:47.476419Z","iopub.status.idle":"2024-01-22T23:18:48.967403Z","shell.execute_reply.started":"2024-01-22T23:05:47.476388Z","shell.execute_reply":"2024-01-22T23:18:48.966177Z"},"trusted":true},"execution_count":null,"outputs":[]}]}