{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":30635,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# CIFAR10 dataset \nkaggle: https://www.kaggle.com/xxxxxxxyyyyyyyyy/cifar10-sebastianomorson\n\nwandb: https://wandb.ai/monkeys777/CIFAR-10withResNet18","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))\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-22T22:55:12.663548Z","iopub.execute_input":"2024-01-22T22:55:12.664020Z","iopub.status.idle":"2024-01-22T22:55:13.094228Z","shell.execute_reply.started":"2024-01-22T22:55:12.663983Z","shell.execute_reply":"2024-01-22T22:55:13.093252Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Import everything needed","metadata":{}},{"cell_type":"code","source":"import wandb\nfrom kaggle_secrets import UserSecretsClient\n\nuser_secrets = UserSecretsClient()\nsecret_value_0 = user_secrets.get_secret(\"wandb.api.key\")\nwandb.login(key=secret_value_0)\nwandb.init(project='CIFAR-10withResNet18', save_code=True)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:55:13.096695Z","iopub.execute_input":"2024-01-22T22:55:13.097300Z","iopub.status.idle":"2024-01-22T22:55:47.873185Z","shell.execute_reply.started":"2024-01-22T22:55:13.097262Z","shell.execute_reply":"2024-01-22T22:55:47.872107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\n\n","metadata":{"execution":{"iopub.status.busy":"2024-01-22T22:55:47.877360Z","iopub.execute_input":"2024-01-22T22:55:47.877700Z","iopub.status.idle":"2024-01-22T22:55:51.499829Z","shell.execute_reply.started":"2024-01-22T22:55:47.877670Z","shell.execute_reply":"2024-01-22T22:55:51.498704Z"},"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-22T22:55:51.501373Z","iopub.execute_input":"2024-01-22T22:55:51.501777Z","iopub.status.idle":"2024-01-22T22:56:10.826591Z","shell.execute_reply.started":"2024-01-22T22:55:51.501727Z","shell.execute_reply":"2024-01-22T22:56:10.825358Z"},"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-22T22:56:10.829953Z","iopub.execute_input":"2024-01-22T22:56:10.830301Z","iopub.status.idle":"2024-01-22T22:57:18.654886Z","shell.execute_reply.started":"2024-01-22T22:56:10.830269Z","shell.execute_reply":"2024-01-22T22:57:18.653622Z"},"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-22T22:57:18.657169Z","iopub.execute_input":"2024-01-22T22:57:18.657608Z","iopub.status.idle":"2024-01-22T23:20:23.439511Z","shell.execute_reply.started":"2024-01-22T22:57:18.657565Z","shell.execute_reply":"2024-01-22T23:20:23.438027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_dir = '/kaggle/working/'","metadata":{"execution":{"iopub.status.busy":"2024-01-22T23:20:23.442303Z","iopub.execute_input":"2024-01-22T23:20:23.442785Z","iopub.status.idle":"2024-01-22T23:20:23.794665Z","shell.execute_reply.started":"2024-01-22T23:20:23.442722Z","shell.execute_reply":"2024-01-22T23:20:23.793602Z"},"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-22T23:20:23.796329Z","iopub.execute_input":"2024-01-22T23:20:23.796746Z","iopub.status.idle":"2024-01-22T23:20:24.233141Z","shell.execute_reply.started":"2024-01-22T23:20:23.796698Z","shell.execute_reply":"2024-01-22T23:20:24.231729Z"},"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-22T23:20:24.236532Z","iopub.execute_input":"2024-01-22T23:20:24.237020Z","iopub.status.idle":"2024-01-22T23:20:24.655648Z","shell.execute_reply.started":"2024-01-22T23:20:24.236974Z","shell.execute_reply":"2024-01-22T23:20:24.654392Z"},"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-22T23:20:24.657315Z","iopub.execute_input":"2024-01-22T23:20:24.657800Z","iopub.status.idle":"2024-01-22T23:21:37.557324Z","shell.execute_reply.started":"2024-01-22T23:20:24.657727Z","shell.execute_reply":"2024-01-22T23:21:37.556131Z"},"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":"img_size = 32\nwandb.log({'image size':img_size})\n\ntransform_train = torchvision.transforms.Compose([\n    torchvision.transforms.ToTensor(),\n    transforms.ColorJitter(brightness=0.1,contrast = 0.1 ,saturation =0.1 ),\n    torchvision.transforms.RandomHorizontalFlip(0.3),\n    torchvision.transforms.RandomVerticalFlip(0.3),\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-22T23:21:37.558944Z","iopub.execute_input":"2024-01-22T23:21:37.559349Z","iopub.status.idle":"2024-01-22T23:21:37.930025Z","shell.execute_reply.started":"2024-01-22T23:21:37.559310Z","shell.execute_reply":"2024-01-22T23:21:37.928925Z"},"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-22T23:21:37.931565Z","iopub.execute_input":"2024-01-22T23:21:37.931982Z","iopub.status.idle":"2024-01-22T23:21:40.534635Z","shell.execute_reply.started":"2024-01-22T23:21:37.931943Z","shell.execute_reply":"2024-01-22T23:21:40.533534Z"},"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":"markdown","source":"## Import resnet18 model, pretrained","metadata":{}},{"cell_type":"code","source":"import torchvision.models as models\nresnet18 = models.resnet18(pretrained=True)\nresnet18.fc = nn.Linear(in_features=512, out_features=10, bias=True)\nnn.init.xavier_normal_(resnet18.fc.weight)\nnn.init.constant_(resnet18.fc.bias, 0)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T23:21:40.536117Z","iopub.execute_input":"2024-01-22T23:21:40.536443Z","iopub.status.idle":"2024-01-22T23:21:41.805929Z","shell.execute_reply.started":"2024-01-22T23:21:40.536414Z","shell.execute_reply":"2024-01-22T23:21:41.804684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#show resnet18 description\nprint(resnet18)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T23:21:41.811743Z","iopub.execute_input":"2024-01-22T23:21:41.812801Z","iopub.status.idle":"2024-01-22T23:21:42.203140Z","shell.execute_reply.started":"2024-01-22T23:21:41.812733Z","shell.execute_reply":"2024-01-22T23:21:42.201956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Define train and test methods","metadata":{}},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\n#criterion = nn.NLLLoss()\ndef train(model, device, train_loader, train_valid_loader, opt, epoch):\n    mean_train_losses = []\n    mean_valid_losses = []\n    valid_acc_list = []\n    train_losses = []\n    valid_losses = []\n    model.train()\n    for batch_id, (images, target) in enumerate(train_loader):\n        images, target = images.to(device), target.to(device)\n\n        opt.zero_grad()\n        output = model(images)\n        loss = criterion(output,target)\n        loss.backward()\n        opt.step()\n        train_losses.append(loss.item())\n        \n    model.eval()\n    val_losses = 0\n    val_correct = 0\n    correct = 0\n    total = 0\n    with torch.no_grad():\n        \n        for batch_id, (images, target) in enumerate (train_valid_loader):\n            \n            images, target = images.to(device), target.to(device)\n            output = model(images)\n            # calculate the loss\n            loss = criterion(output, target)\n            # update running validation loss \n            valid_losses.append(loss.item())\n            \n            _, predicted = torch.max(output.data, 1)\n            \n            correct += (predicted == target).sum().item()\n            total += target.size(0)\n\n    mean_train_losses.append(np.mean(train_losses))\n    mean_valid_losses.append(np.mean(valid_losses))\n    \n    accuracy = 100*correct/total\n    valid_acc_list.append(accuracy)\n    print('epoch : {}, train loss : {:.4f}, valid loss : {:.4f}, valid acc : {:.2f}%'\\\n         .format(epoch+1, np.mean(train_losses), np.mean(valid_losses), accuracy))\n    \n    wandb.log({'train_loss':mean_train_losses[-1]})\n    wandb.log({'val_loss':mean_valid_losses[-1]})\n    wandb.log({'val_accuracy':valid_acc_list[-1]})\n        \ndef test(model, device, test_loader):\n    model.eval()\n    test_loss = 0\n    correct = 0\n    with torch.no_grad():\n        for batch_id, (images, target) in test_loader:\n            images, target = images.to(device), target.to(device)\n            output = model(images)\n            test_loss += F.nll_loss(output, target, reduction='sum').item()\n            pred = output.argmax(dim=1, keepdim=True)\n            correct += pred.eq(target.view_as(pred)).sum().item()\n\n    test_loss /= len(test_loader.dataset)\n\n    print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n        test_loss, correct, len(test_loader.dataset),\n        100. * correct / len(test_loader.dataset)))\n    return test_loss","metadata":{"execution":{"iopub.status.busy":"2024-01-22T23:21:42.204905Z","iopub.execute_input":"2024-01-22T23:21:42.205251Z","iopub.status.idle":"2024-01-22T23:21:42.604084Z","shell.execute_reply.started":"2024-01-22T23:21:42.205212Z","shell.execute_reply":"2024-01-22T23:21:42.602896Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.optim.lr_scheduler import StepLR\n\nlr = 0.01\nstep_size = 1\ngamma=0.7\nepoch = 10\nopt = \"SGD\" # \"Adam\"\n\nsaved = False #True if I want to use a saved model\n\ndev_name = \"cuda\" if torch.cuda.is_available() else \"mps\" if torch.backends.mps.is_available() else \"cpu\"\n    \nprint(\"Using {} to traing the model\".format(dev_name))\ndevice = torch.device(dev_name)\nmodel = resnet18.to(device)\n\nif device==\"cuda\":\n    model = torch.nn.DataParallel(model)\n\n\nif not saved:\n    \n    wandb.log({'lr': lr})\n    wandb.log({'step_size': step_size})\n    wandb.log({'gamma': gamma})\n    wandb.log({'epoch': epoch})\n    wandb.log({'optimizer': opt})\n\n\n    if opt == \"Adam\":\n        opt = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=0.5)\n    elif opt == \"SGD\":\n        opt = torch.optim.SGD(model.parameters(), lr=lr,momentum=0.1)\n\n\n    # Decreases the learning rate of each parameter group by gamma every 1 epoch\n    #scheduler = StepLR(opt, step_size=step_size, gamma=gamma)\n    for epoch in range(0, epoch):\n        train(model, device, train_iter,train_valid_iter, opt, epoch)\n        #scheduler.step()\n    \n    #torch.save(model.state_dict(), \"/kaggle/input/digit-recognizer/model\")\n\n    \nelse:\n    print(\"Miaoooo\")\n    #model.load_state_dict(torch.load(\"/kaggle/input/digit-recognizer/model\"))","metadata":{"execution":{"iopub.status.busy":"2024-01-22T23:49:15.361911Z","iopub.execute_input":"2024-01-22T23:49:15.362659Z","iopub.status.idle":"2024-01-23T00:11:02.078194Z","shell.execute_reply.started":"2024-01-22T23:49:15.362625Z","shell.execute_reply":"2024-01-23T00:11:02.077066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math\nwith torch.no_grad():\n    model.eval()\n    test_pred = []\n    for i,(images, target) in enumerate(test_iter):\n        if i%100==0: print(\"Test id: \", i)\n        images, target = images.to(device), target.to(device)\n        outputs = model(images)\n        test_pred.extend(outputs.argmax(dim=1).type(torch.int32).cpu().numpy())\n\nids = list(range(1, len(test_ds)+1))\nids.sort(key=lambda x: str(x))\ndf = pd.DataFrame({'id': ids, 'label': test_pred})\ndf['label'] = df['label'].apply(lambda x: train_ds.classes[x])\ndf.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-23T00:11:22.833663Z","iopub.execute_input":"2024-01-23T00:11:22.834122Z","iopub.status.idle":"2024-01-23T00:14:36.523821Z","shell.execute_reply.started":"2024-01-23T00:11:22.834090Z","shell.execute_reply":"2024-01-23T00:14:36.522660Z"},"trusted":true},"execution_count":null,"outputs":[]}]}