{"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":"markdown","source":"### https://www.kaggle.com/c/cifar-10","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":"2022-01-25T07:58:30.600073Z","iopub.execute_input":"2022-01-25T07:58:30.600631Z","iopub.status.idle":"2022-01-25T07:58:30.610054Z","shell.execute_reply.started":"2022-01-25T07:58:30.600594Z","shell.execute_reply":"2022-01-25T07:58:30.609206Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2022-01-25T07:58:47.719387Z","iopub.execute_input":"2022-01-25T07:58:47.719981Z","iopub.status.idle":"2022-01-25T07:58:50.21734Z","shell.execute_reply.started":"2022-01-25T07:58:47.719933Z","shell.execute_reply":"2022-01-25T07:58:50.216444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Wandb","metadata":{}},{"cell_type":"code","source":"import wandb\nfrom kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient()\nsecret_value_0 = user_secrets.get_secret(\"WANDB_KEY\")\nwandb.login(key=secret_value_0)\nwandb.init(project='cifar-10', save_code=True)","metadata":{"execution":{"iopub.status.busy":"2022-01-25T07:58:53.302128Z","iopub.execute_input":"2022-01-25T07:58:53.302453Z","iopub.status.idle":"2022-01-25T07:59:05.238094Z","shell.execute_reply.started":"2022-01-25T07:58:53.302422Z","shell.execute_reply":"2022-01-25T07:59:05.237196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Unzip datasets","metadata":{}},{"cell_type":"markdown","source":"# WARNING: It can take a lot of time to uncompress!","metadata":{}},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2022-01-25T09:55:24.364872Z","iopub.execute_input":"2022-01-25T09:55:24.365383Z","iopub.status.idle":"2022-01-25T09:56:12.947523Z","shell.execute_reply.started":"2022-01-25T09:55:24.365346Z","shell.execute_reply":"2022-01-25T09:56:12.946551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python -m py7zr x /kaggle/input/cifar-10/test.7z","metadata":{},"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-25T09:54:22.249773Z","iopub.execute_input":"2022-01-25T09:54:22.25011Z","iopub.status.idle":"2022-01-25T09:54:35.346911Z","shell.execute_reply.started":"2022-01-25T09:54:22.250074Z","shell.execute_reply":"2022-01-25T09:54:35.346031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_dir = '/kaggle/working/'","metadata":{"execution":{"iopub.status.busy":"2022-01-25T07:59:10.045342Z","iopub.execute_input":"2022-01-25T07:59:10.047205Z","iopub.status.idle":"2022-01-25T07:59:11.99867Z","shell.execute_reply.started":"2022-01-25T07:59:10.047128Z","shell.execute_reply":"2022-01-25T07:59:11.997564Z"},"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-25T07:59:14.182444Z","iopub.execute_input":"2022-01-25T07:59:14.182708Z","iopub.status.idle":"2022-01-25T07:59:15.318257Z","shell.execute_reply.started":"2022-01-25T07:59:14.182681Z","shell.execute_reply":"2022-01-25T07:59:15.317352Z"},"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-25T07:59:21.214417Z","iopub.execute_input":"2022-01-25T07:59:21.214674Z","iopub.status.idle":"2022-01-25T07:59:22.299389Z","shell.execute_reply.started":"2022-01-25T07:59:21.214647Z","shell.execute_reply":"2022-01-25T07:59:22.29849Z"},"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-25T07:59:25.950536Z","iopub.execute_input":"2022-01-25T07:59:25.950818Z","iopub.status.idle":"2022-01-25T07:59:27.033961Z","shell.execute_reply.started":"2022-01-25T07:59:25.950787Z","shell.execute_reply":"2022-01-25T07:59:27.033073Z"},"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-25T07:59:28.793877Z","iopub.execute_input":"2022-01-25T07:59:28.794129Z","iopub.status.idle":"2022-01-25T07:59:29.860433Z","shell.execute_reply.started":"2022-01-25T07:59:28.794104Z","shell.execute_reply":"2022-01-25T07:59:29.859528Z"},"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-25T07:59:32.389758Z","iopub.execute_input":"2022-01-25T07:59:32.390006Z","iopub.status.idle":"2022-01-25T07:59:33.869371Z","shell.execute_reply.started":"2022-01-25T07:59:32.389981Z","shell.execute_reply":"2022-01-25T07:59:33.866901Z"},"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.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":{"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":{"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 to Kaggle your submission file and get your accuracy on the test set","metadata":{}}]}