{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-01-31T10:28:08.144897Z","iopub.execute_input":"2022-01-31T10:28:08.146557Z","iopub.status.idle":"2022-01-31T10:28:08.175744Z","shell.execute_reply.started":"2022-01-31T10:28:08.146477Z","shell.execute_reply":"2022-01-31T10:28:08.174936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:28:08.177295Z","iopub.execute_input":"2022-01-31T10:28:08.177804Z","iopub.status.idle":"2022-01-31T10:28:19.784245Z","shell.execute_reply.started":"2022-01-31T10:28:08.177768Z","shell.execute_reply":"2022-01-31T10:28:19.783202Z"},"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\nimport wandb\n\nfrom kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient()\nsecret_value_0 = user_secrets.get_secret(\"cifar-10\")\n\nwandb.login(key=secret_value_0)\nwandb.init(project=\"Cifar-10\", save_code=True)\n","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:28:19.787933Z","iopub.execute_input":"2022-01-31T10:28:19.788147Z","iopub.status.idle":"2022-01-31T10:28:30.627754Z","shell.execute_reply.started":"2022-01-31T10:28:19.788119Z","shell.execute_reply":"2022-01-31T10:28:30.626869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:28:30.630307Z","iopub.execute_input":"2022-01-31T10:28:30.630584Z","iopub.status.idle":"2022-01-31T10:28:39.552695Z","shell.execute_reply.started":"2022-01-31T10:28:30.630532Z","shell.execute_reply":"2022-01-31T10:28:39.551949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python -m py7zr x /kaggle/input/cifar-10/train.7z","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:28:39.557343Z","iopub.execute_input":"2022-01-31T10:28:39.559831Z","iopub.status.idle":"2022-01-31T10:29:22.995384Z","shell.execute_reply.started":"2022-01-31T10:28:39.559788Z","shell.execute_reply":"2022-01-31T10:29:22.994563Z"},"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":"2022-01-31T10:29:22.997287Z","iopub.execute_input":"2022-01-31T10:29:22.997974Z","iopub.status.idle":"2022-01-31T10:43:27.766422Z","shell.execute_reply.started":"2022-01-31T10:29:22.997929Z","shell.execute_reply":"2022-01-31T10:43:27.765543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_dir = '/kaggle/working/'","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:43:27.771297Z","iopub.execute_input":"2022-01-31T10:43:27.773530Z","iopub.status.idle":"2022-01-31T10:43:28.140713Z","shell.execute_reply.started":"2022-01-31T10:43:27.773486Z","shell.execute_reply":"2022-01-31T10:43:28.140021Z"},"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":"2022-01-31T10:43:28.144988Z","iopub.execute_input":"2022-01-31T10:43:28.147160Z","iopub.status.idle":"2022-01-31T10:43:28.730722Z","shell.execute_reply.started":"2022-01-31T10:43:28.147120Z","shell.execute_reply":"2022-01-31T10:43:28.730039Z"},"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","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:43:28.731986Z","iopub.execute_input":"2022-01-31T10:43:28.732231Z","iopub.status.idle":"2022-01-31T10:43:29.113204Z","shell.execute_reply.started":"2022-01-31T10:43:28.732197Z","shell.execute_reply":"2022-01-31T10:43:29.112553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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'))","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:43:29.118823Z","iopub.execute_input":"2022-01-31T10:43:29.120942Z","iopub.status.idle":"2022-01-31T10:43:29.412027Z","shell.execute_reply.started":"2022-01-31T10:43:29.120902Z","shell.execute_reply":"2022-01-31T10:43:29.411373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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":"2022-01-31T10:43:29.413040Z","iopub.execute_input":"2022-01-31T10:43:29.413881Z","iopub.status.idle":"2022-01-31T10:43:29.787273Z","shell.execute_reply.started":"2022-01-31T10:43:29.413849Z","shell.execute_reply":"2022-01-31T10:43:29.786585Z"},"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":"2022-01-31T10:43:29.788353Z","iopub.execute_input":"2022-01-31T10:43:29.788618Z","iopub.status.idle":"2022-01-31T10:44:30.909462Z","shell.execute_reply.started":"2022-01-31T10:43:29.788562Z","shell.execute_reply":"2022-01-31T10:44:30.908770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform_train = torchvision.transforms.Compose([\n    # TODO,\n    # HorizontalFlip, RandomSizeCrop, \"small\" Color Jitter\n    torchvision.transforms.RandomResizedCrop(32),\n    torchvision.transforms.RandomHorizontalFlip(),\n    torchvision.transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3,hue=0.2),\n    \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\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":"2022-01-31T10:44:30.913909Z","iopub.execute_input":"2022-01-31T10:44:30.914215Z","iopub.status.idle":"2022-01-31T10:44:31.378605Z","shell.execute_reply.started":"2022-01-31T10:44:30.914175Z","shell.execute_reply":"2022-01-31T10:44:31.377907Z"},"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":"2022-01-31T10:44:31.383491Z","iopub.execute_input":"2022-01-31T10:44:31.384819Z","iopub.status.idle":"2022-01-31T10:44:35.045306Z","shell.execute_reply.started":"2022-01-31T10:44:31.384776Z","shell.execute_reply":"2022-01-31T10:44:35.044611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pretrained_net = torchvision.models.resnet18(pretrained=True)\npretrained_net.fc","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:44:35.049698Z","iopub.execute_input":"2022-01-31T10:44:35.052007Z","iopub.status.idle":"2022-01-31T10:44:37.521234Z","shell.execute_reply.started":"2022-01-31T10:44:35.051963Z","shell.execute_reply":"2022-01-31T10:44:37.520503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pretrained_net.fc = nn.Linear(pretrained_net.fc.in_features, 10)\nnn.init.xavier_normal_(pretrained_net.fc.weight)\nnn.init.constant_(pretrained_net.fc.bias, 0);","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:44:37.522676Z","iopub.execute_input":"2022-01-31T10:44:37.523061Z","iopub.status.idle":"2022-01-31T10:44:37.844636Z","shell.execute_reply.started":"2022-01-31T10:44:37.523023Z","shell.execute_reply":"2022-01-31T10:44:37.843887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = 'cuda' if torch.cuda.is_available() else 'cpu'\npretrained_net = pretrained_net.to(device)\nif device == 'cuda':\n    pretrained_net = torch.nn.DataParallel(pretrained_net) # if multiple GPUs use them\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.AdamW(pretrained_net.parameters(), lr=1e-4, weight_decay=0.0001)\nscheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=3, verbose=True, min_lr=1e-5, factor=0.5)","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:44:37.845919Z","iopub.execute_input":"2022-01-31T10:44:37.846160Z","iopub.status.idle":"2022-01-31T10:44:41.120310Z","shell.execute_reply.started":"2022-01-31T10:44:37.846127Z","shell.execute_reply":"2022-01-31T10:44:41.119627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm.notebook import trange, tqdm\n\n\nepochs = 10\nfor epoch in trange(epochs):\n    accurate = 0\n    total = 0\n    losses = 0\n    for X, y in tqdm(train_iter):\n        X = X.to(device)\n        y = y.to(device)\n        y_pred = pretrained_net(X)\n        loss = criterion(y_pred, y)\n        score, predicted = torch.max(y_pred, 1)\n        accurate += (y == predicted).sum().float()\n        losses += loss.item()\n        total += len(y)\n\n        # zero the gradients before running\n        # the backward pass.\n        optimizer.zero_grad()\n\n        # Backward pass to compute the gradient\n        # of loss w.r.t our learnable params. \n        loss.backward()\n\n        # Update params\n        optimizer.step()\n    \n    wandb.log({\n            'train_loss': losses / len(train_iter),\n            'train_accuracy': accurate / total\n    })\n    \n    \n    with torch.no_grad():\n        pretrained_net.eval()\n        accurate = 0\n        total = 0\n        losses = 0\n        for X, y in tqdm(valid_iter):\n            X = X.to(device)\n            y = y.to(device)\n            y_pred = pretrained_net(X)\n            loss = criterion(y_pred, y)\n            score, predicted = torch.max(y_pred, 1)\n            accurate += (y == predicted).sum().float()\n            losses += loss.item()\n            total += len(y)\n            \n        \n        wandb.log({\n            'valid_loss': losses / len(valid_iter),\n            'valid_accuracy': accurate / total,\n        })","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:44:41.121626Z","iopub.execute_input":"2022-01-31T10:44:41.122192Z","iopub.status.idle":"2022-01-31T10:56:21.392178Z","shell.execute_reply.started":"2022-01-31T10:44:41.122148Z","shell.execute_reply":"2022-01-31T10:56:21.391472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = []\npretrained_net.eval()\nwith torch.no_grad():\n    for X, _ in tqdm(test_iter):\n        X = X.to(device)\n        predictions.extend(pretrained_net(X).argmax(dim=1).type(torch.int32).cpu().numpy())\nids = list(range(1, len(test_ds)+1))\nids.sort(key=lambda x: str(x))\n\ndf = pd.DataFrame({'id': ids, 'label': predictions})\ndf['label'] = df['label'].apply(lambda x: train_ds.classes[x]) \ndf.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:56:21.393487Z","iopub.execute_input":"2022-01-31T10:56:21.394013Z","iopub.status.idle":"2022-01-31T10:59:17.080090Z","shell.execute_reply.started":"2022-01-31T10:56:21.393970Z","shell.execute_reply":"2022-01-31T10:59:17.079291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.save(pretrained_net.state_dict(), 'pretrained_net.pt')","metadata":{"execution":{"iopub.status.busy":"2022-01-31T10:59:17.084401Z","iopub.execute_input":"2022-01-31T10:59:17.084646Z","iopub.status.idle":"2022-01-31T10:59:17.594901Z","shell.execute_reply.started":"2022-01-31T10:59:17.084612Z","shell.execute_reply":"2022-01-31T10:59:17.594182Z"},"trusted":true},"execution_count":null,"outputs":[]}]}