{"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":"none","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":30636,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Kaggele Note book: https://www.kaggle.com/code/hemalathaaae/cifar-10","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5"}},{"cell_type":"markdown","source":"Wandb Link : https://wandb.ai/hemalathaa/CIFAR%2010%20Project/workspace?workspace=user-hemalathaaelumalai","metadata":{}},{"cell_type":"markdown","source":"Kaggle Submission : https://www.kaggle.com/competitions/cifar-10/submissions","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":{"execution":{"iopub.status.busy":"2024-01-22T20:14:10.181187Z","iopub.execute_input":"2024-01-22T20:14:10.181576Z","iopub.status.idle":"2024-01-22T20:14:10.62924Z","shell.execute_reply.started":"2024-01-22T20:14:10.181544Z","shell.execute_reply":"2024-01-22T20:14:10.628407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Import everything needed","metadata":{}},{"cell_type":"code","source":"import glob\nimport numpy as np\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)\nimport time\nimport wandb\nwandb.init(project='CIFAR 10 Project', save_code=True,)\n","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:14:25.68251Z","iopub.execute_input":"2024-01-22T20:14:25.683078Z","iopub.status.idle":"2024-01-22T20:15:28.359507Z","shell.execute_reply.started":"2024-01-22T20:14:25.683043Z","shell.execute_reply":"2024-01-22T20:15:28.358182Z"},"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:15:37.058996Z","iopub.execute_input":"2024-01-22T20:15:37.059523Z","iopub.status.idle":"2024-01-22T20:15:56.267858Z","shell.execute_reply.started":"2024-01-22T20:15:37.05948Z","shell.execute_reply":"2024-01-22T20:15:56.266625Z"},"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":"stime = time.time()\n!python -m py7zr x /kaggle/input/cifar-10/train.7z\netime = time.time()\ncompletiontime = etime - stime\nprint(completiontime)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:16:01.423929Z","iopub.execute_input":"2024-01-22T20:16:01.424399Z","iopub.status.idle":"2024-01-22T20:17:08.684259Z","shell.execute_reply.started":"2024-01-22T20:16:01.42436Z","shell.execute_reply":"2024-01-22T20:17:08.683359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"stime1 = time.time()\n!python -m py7zr x /kaggle/input/cifar-10/test.7z\netime1 = time.time()\ncompletiontime1 = etime1 - stime1\nprint(completiontime1)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:17:58.500843Z","iopub.execute_input":"2024-01-22T20:17:58.501438Z","iopub.status.idle":"2024-01-22T20:40:51.005353Z","shell.execute_reply.started":"2024-01-22T20:17:58.501389Z","shell.execute_reply":"2024-01-22T20:40:51.004063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_dir = '/kaggle/working/'","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:40:51.007636Z","iopub.execute_input":"2024-01-22T20:40:51.008563Z","iopub.status.idle":"2024-01-22T20:40:51.525106Z","shell.execute_reply.started":"2024-01-22T20:40:51.008514Z","shell.execute_reply":"2024-01-22T20:40:51.52405Z"},"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-22T20:40:51.526601Z","iopub.execute_input":"2024-01-22T20:40:51.527052Z","iopub.status.idle":"2024-01-22T20:40:52.226927Z","shell.execute_reply.started":"2024-01-22T20:40:51.527011Z","shell.execute_reply":"2024-01-22T20:40:52.225819Z"},"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    label_mapping = {'airplane': 0, 'automobile': 1, 'bird': 2, 'cat': 3, 'deer': 4, 'dog': 5, 'frog': 6, 'horse': 7, 'ship':8, 'truck':9}\n    labels = {key: label_mapping[value] for key, value in labels.items()}\n    reorg_test(data_dir)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:40:52.231315Z","iopub.execute_input":"2024-01-22T20:40:52.231739Z","iopub.status.idle":"2024-01-22T20:40:52.841169Z","shell.execute_reply.started":"2024-01-22T20:40:52.231707Z","shell.execute_reply":"2024-01-22T20:40:52.83805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 32\nvalid_ratio = 0.1\nreorg_cifar10_data(data_dir, valid_ratio)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:40:52.843855Z","iopub.execute_input":"2024-01-22T20:40:52.846331Z","iopub.status.idle":"2024-01-22T20:42:53.025064Z","shell.execute_reply.started":"2024-01-22T20:40:52.846266Z","shell.execute_reply":"2024-01-22T20:42:53.023807Z"},"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.RandomResizedCrop(224),    # Random crop and resize\n    torchvision.transforms.RandomHorizontalFlip(),\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.Resize(256),\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-22T20:42:53.027099Z","iopub.execute_input":"2024-01-22T20:42:53.028015Z","iopub.status.idle":"2024-01-22T20:42:53.563279Z","shell.execute_reply.started":"2024-01-22T20:42:53.027973Z","shell.execute_reply":"2024-01-22T20:42:53.562479Z"},"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-22T20:42:53.56516Z","iopub.execute_input":"2024-01-22T20:42:53.565854Z","iopub.status.idle":"2024-01-22T20:42:56.567211Z","shell.execute_reply.started":"2024-01-22T20:42:53.565815Z","shell.execute_reply":"2024-01-22T20:42:56.566066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:42:56.568717Z","iopub.execute_input":"2024-01-22T20:42:56.569114Z","iopub.status.idle":"2024-01-22T20:42:57.105626Z","shell.execute_reply.started":"2024-01-22T20:42:56.569082Z","shell.execute_reply":"2024-01-22T20:42:57.104544Z"},"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)\nmodel.fc = nn.Sequential(\n    nn.Dropout(0.5),\n    nn.Linear(model.fc.in_features, 10))\n#model.fc = nn.Linear(model.fc.in_features, 10)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:42:57.106763Z","iopub.execute_input":"2024-01-22T20:42:57.108067Z","iopub.status.idle":"2024-01-22T20:42:58.409601Z","shell.execute_reply.started":"2024-01-22T20:42:57.108036Z","shell.execute_reply":"2024-01-22T20:42:58.408521Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(model)","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:42:58.414046Z","iopub.execute_input":"2024-01-22T20:42:58.414475Z","iopub.status.idle":"2024-01-22T20:42:59.145439Z","shell.execute_reply.started":"2024-01-22T20:42:58.414431Z","shell.execute_reply":"2024-01-22T20:42:59.14435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.optim.lr_scheduler import StepLR\nfrom torch.optim import Adam\n\n# Define loss function and optimizer\ncriterion = nn.CrossEntropyLoss()\n#optimizer = optim.SGD(model.parameters(), lr=1e-05,momentum=0.1, nesterov=True)\n#optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\noptimizer = Adam(model.parameters(), lr=0.0001)\n# After defining the optimizer\nscheduler = StepLR(optimizer, step_size=5, gamma=0.1)\n\n\n# Train the model\nnum_epochs = 10\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel=model.to(device)\n\nfor epoch in range(num_epochs):\n    model.train()\n    running_loss = 0.0\n    correct_train = 0\n    total_train = 0\n    start_time = time.time()     \n    print(f'Epoch [{epoch + 1}/{num_epochs}]')\n    for inputs, labels in train_iter:\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        \n        running_loss += loss.item()\n        \n                # Calculate accuracy\n        _, predicted = torch.max(outputs.data, 1)\n        total_train += labels.size(0)\n        correct_train += (predicted == labels).sum().item()\n\n    # Print training loss at the end of each epoch\n    end_time = time.time()  # Record the end time for the epoch\n    epoch_time = end_time - start_time  # Calculate the time taken for the epoch\n    average_loss = running_loss / len(train_iter)\n    train_accuracy = correct_train / total_train  \n    # Append training metrics to lists\n    #train_losses.append(average_loss)\n    #train_accuracies.append(train_accuracy)\n    # Log training accuracy and loss to WandB\n    wandb.log({\"train_loss\": average_loss, \"train_accuracy\": train_accuracy})\n    print(f'Training Loss: {average_loss:.2f}, Training Accuracy: {train_accuracy:.2f},Time: {epoch_time:.2f} seconds')\n    \n    # Validate the model\n    model.eval()\n    correct_val = 0\n    total_val = 0\n    val_running_loss = 0.0    \n    start_val_time = time.time()\n    with torch.no_grad():\n        for inputs, labels in valid_iter:\n            inputs, labels = inputs.to(device), labels.to(device)\n            outputs = model(inputs)            \n            val_loss = criterion(outputs, labels)\n            val_running_loss += val_loss.item()\n            _, predicted = torch.max(outputs.data, 1)\n            total_val += labels.size(0)\n            correct_val += (predicted == labels).sum().item()\n\n     # Print validation loss and accuracy\n    validation_loss = val_running_loss / len(valid_iter)\n    validation_accuracy = correct_val / total_val\n    end_val_time = time.time()  # Record the end time for validation\n    val_epoch_time = end_val_time - start_val_time\n    # Append validation metrics to lists\n    #val_losses.append(validation_loss)\n    #val_accuracies.append(validation_accuracy)\n    # Log Validation accuracy and loss to WandB\n    wandb.log({\"validation_loss\": validation_loss, \"validation_accuracy\": validation_accuracy})\n    print(f'Validation Loss: {validation_loss :.2f}, Validation Accuracy: {validation_accuracy :.2f}, Validation Time: {val_epoch_time :.2f} seconds')\n    scheduler.step()","metadata":{"execution":{"iopub.status.busy":"2024-01-22T20:42:59.147258Z","iopub.execute_input":"2024-01-22T20:42:59.148153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels_name = [\"airplane\", \"automobile\", \"bird\", \"cat\", \"deer\", \"dog\", \"frog\", \"horse\", \"ship\", \"truck\"]\nlabels_list = {str(i): labels_name[i] for i in range(10)}\n\ndirectory = '/kaggle/working/test'\nImageId = sorted([(''.join(filter(str.isdigit, name))) for name in os.listdir(directory)])\n\nwith torch.no_grad():\n    model.eval()\n    test_pred = torch.LongTensor()\n    for i, data in enumerate(test_iter):\n        output = model(data[0].to(device)).argmax(1)\n        predicted = output.cpu()\n        test_pred = torch.cat((test_pred, predicted), dim=0)\n\n# Create the DataFrame\nout_df = pd.DataFrame(np.c_[ImageId, test_pred.numpy()], columns=['id', 'label']).astype({'id': 'int', 'label': 'str'})\nout_df['label'] = out_df['label'].map(labels_list)\n\n# Sort the DataFrame by 'id' as strings\nout_df['id'] = out_df['id'].astype(str)\nout_df = out_df.sort_values(by='id')\n\nout_df.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"  ","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}