{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30746,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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)\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom sklearn.model_selection import train_test_split \nimport scikitplot as skplt\n\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\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":"2024-08-04T06:03:23.991538Z","iopub.execute_input":"2024-08-04T06:03:23.991947Z","iopub.status.idle":"2024-08-04T06:03:29.592455Z","shell.execute_reply.started":"2024-08-04T06:03:23.991915Z","shell.execute_reply":"2024-08-04T06:03:29.591058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv('../input/digit-recognizer/train.csv')\ntest = pd.read_csv('../input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:03:29.594671Z","iopub.execute_input":"2024-08-04T06:03:29.595191Z","iopub.status.idle":"2024-08-04T06:03:36.450585Z","shell.execute_reply.started":"2024-08-04T06:03:29.595159Z","shell.execute_reply":"2024-08-04T06:03:36.449343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:03:36.452093Z","iopub.execute_input":"2024-08-04T06:03:36.452527Z","iopub.status.idle":"2024-08-04T06:03:36.485194Z","shell.execute_reply.started":"2024-08-04T06:03:36.452494Z","shell.execute_reply":"2024-08-04T06:03:36.483954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels_np = train_data[\"label\"].to_numpy()\ntrain_features_np = train_data.iloc[:, 1:].to_numpy()\ntest_np = test.to_numpy()","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:10:38.520912Z","iopub.execute_input":"2024-08-04T06:10:38.521358Z","iopub.status.idle":"2024-08-04T06:10:38.528549Z","shell.execute_reply.started":"2024-08-04T06:10:38.521324Z","shell.execute_reply":"2024-08-04T06:10:38.527160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train, validation, train_label, validation_label = train_test_split(train_features_np, train_labels_np, test_size=0.25)\nprint(train.shape)\nprint(validation.shape)\nprint(train_label.shape)\nprint(validation_label.shape)","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:03:36.497632Z","iopub.execute_input":"2024-08-04T06:03:36.498367Z","iopub.status.idle":"2024-08-04T06:03:36.960946Z","shell.execute_reply.started":"2024-08-04T06:03:36.498320Z","shell.execute_reply":"2024-08-04T06:03:36.959885Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_tensor = torch.as_tensor(train).type(torch.FloatTensor)\ntrain_label = torch.as_tensor(train_label)\n\nvalidation_tensor = torch.as_tensor(validation).type(torch.FloatTensor)\nvalidation_label = torch.as_tensor(validation_label)\n\ntest_tensor = torch.as_tensor(test_np).type(torch.FloatTensor)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:10:45.973552Z","iopub.execute_input":"2024-08-04T06:10:45.974600Z","iopub.status.idle":"2024-08-04T06:10:46.146804Z","shell.execute_reply.started":"2024-08-04T06:10:45.974547Z","shell.execute_reply":"2024-08-04T06:10:46.145238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class FNN(nn.Module):\n    def __init__(self):\n        super(FNN, self).__init__()\n        self.linear1 = nn.Linear(in_features=784, out_features=420)\n        self.linear2 = nn.Linear(in_features=420, out_features=360)\n        self.linear3 = nn.Linear(in_features=360, out_features=144)\n        self.linear4 = nn.Linear(in_features=144, out_features=10)\n    \n    def forward(self, x):\n        x = x.view(-1, 784)\n        x = F.relu(self.linear1(x))\n        x = F.relu(self.linear2(x))\n        x = F.relu(self.linear3(x))\n        x = self.linear4(x)\n        return x","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:03:37.063360Z","iopub.execute_input":"2024-08-04T06:03:37.063922Z","iopub.status.idle":"2024-08-04T06:03:37.074674Z","shell.execute_reply.started":"2024-08-04T06:03:37.063887Z","shell.execute_reply":"2024-08-04T06:03:37.073367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def training_loop(dataloader, epochs, model, criterion, optimizer):\n    model.train()\n    \n    for epoch in range(epochs):\n        for data, labels in dataloader:\n            optimizer.zero_grad()\n            predictions = model(data)\n            loss = criterion(predictions, labels)\n            loss.backward()\n            optimizer.step()","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:03:37.076155Z","iopub.execute_input":"2024-08-04T06:03:37.076613Z","iopub.status.idle":"2024-08-04T06:03:37.090684Z","shell.execute_reply.started":"2024-08-04T06:03:37.076579Z","shell.execute_reply":"2024-08-04T06:03:37.089343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.manual_seed(42)\n\nbatch_size = 128\ntrain_dataset = torch.utils.data.TensorDataset(train_tensor, train_label)\ntrainloader = torch.utils.data.DataLoader(train_dataset, batch_size = batch_size, shuffle = True)\n\n\nepochs = 40\n\nmodel = FNN()\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr = 1e-4)\ntraining_loop(trainloader, epochs, model, criterion, optimizer)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:07:32.697877Z","iopub.status.idle":"2024-08-04T06:07:32.698491Z","shell.execute_reply.started":"2024-08-04T06:07:32.698176Z","shell.execute_reply":"2024-08-04T06:07:32.698201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_accuracy(predictions, true_labels):\n    _, predicted = torch.max(predictions, 1)\n    corrects = (predicted == true_labels).sum()\n    accuracy = 100.0 * corrects/len(true_labels)\n    return accuracy.item()","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:08:03.764356Z","iopub.execute_input":"2024-08-04T06:08:03.764849Z","iopub.status.idle":"2024-08-04T06:08:03.771918Z","shell.execute_reply.started":"2024-08-04T06:08:03.764817Z","shell.execute_reply":"2024-08-04T06:08:03.770711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.eval()\n\nval_pred = model(validation_tensor)\nval_loss = criterion(val_pred, validation_label)\nval_acc = get_accuracy(val_pred, validation_label)\n\nprint(\"Loss: \", str(val_loss.item()), \"Accuracy: \", str(val_acc))\n","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:08:46.985577Z","iopub.execute_input":"2024-08-04T06:08:46.986743Z","iopub.status.idle":"2024-08-04T06:08:47.114684Z","shell.execute_reply.started":"2024-08-04T06:08:46.986699Z","shell.execute_reply":"2024-08-04T06:08:47.113470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_pred = model(test_tensor)\n_, test_predicted = torch.max(test_pred.data,1)\noutput = pd.DataFrame({'ImageId': test.index + 1,\n                       'Label': test_predicted})\noutput.to_csv('submission.csv', index=False)\noutput.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-04T06:11:39.944193Z","iopub.execute_input":"2024-08-04T06:11:39.944637Z","iopub.status.idle":"2024-08-04T06:11:40.346425Z","shell.execute_reply.started":"2024-08-04T06:11:39.944604Z","shell.execute_reply":"2024-08-04T06:11:40.345284Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}