{"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":"2021-10-15T02:34:52.228398Z","iopub.execute_input":"2021-10-15T02:34:52.228737Z","iopub.status.idle":"2021-10-15T02:34:52.242993Z","shell.execute_reply.started":"2021-10-15T02:34:52.228646Z","shell.execute_reply":"2021-10-15T02:34:52.242150Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = pd.read_csv(\"/kaggle/input/2021-ai-w7-p1/mnist_train.csv\",index_col=0)\nx_test = pd.read_csv(\"/kaggle/input/2021-ai-w7-p1/mnist_test.csv\",index_col=0)","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:34:52.244538Z","iopub.execute_input":"2021-10-15T02:34:52.245120Z","iopub.status.idle":"2021-10-15T02:35:01.463030Z","shell.execute_reply.started":"2021-10-15T02:34:52.245085Z","shell.execute_reply":"2021-10-15T02:35:01.462191Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = np.array(x_train)\ny_train = x_train[:,-1]\nx_train = x_train[:,:-1]\nx_test = np.array(x_test)","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:01.465862Z","iopub.execute_input":"2021-10-15T02:35:01.466120Z","iopub.status.idle":"2021-10-15T02:35:01.633322Z","shell.execute_reply.started":"2021-10-15T02:35:01.466095Z","shell.execute_reply":"2021-10-15T02:35:01.632276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nfig, axes = plt.subplots(1, 4)\n\nfor i, ax in enumerate(axes.flat):\n    ax.imshow(1 - x_train[i].reshape((28, 28)), cmap=\"gray\")\n    ax.set(title=f\"{y_train[i]}\")\n    ax.set_axis_off()","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:01.635033Z","iopub.execute_input":"2021-10-15T02:35:01.635375Z","iopub.status.idle":"2021-10-15T02:35:01.832722Z","shell.execute_reply.started":"2021-10-15T02:35:01.635332Z","shell.execute_reply":"2021-10-15T02:35:01.831836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport random\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nrandom.seed(777)\ntorch.manual_seed(777)\nif device == 'cuda':\n  torch.cuda.manual_seed_all(777)\n\nx_train = torch.tensor(x_train, dtype=torch.float)/255\nx_test = torch.tensor(x_test, dtype=torch.float)/255\ny_train = torch.tensor([int(x) for x in y_train])","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:01.834386Z","iopub.execute_input":"2021-10-15T02:35:01.834727Z","iopub.status.idle":"2021-10-15T02:35:03.377819Z","shell.execute_reply.started":"2021-10-15T02:35:01.834691Z","shell.execute_reply":"2021-10-15T02:35:03.376970Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MNSIT_DNN_Model(torch.nn.Module):\n    \n    def __init__(self):\n        super(MNSIT_DNN_Model, self).__init__()\n        self.linear1 = torch.nn.Linear(784,512,bias=True)\n        self.linear2 = torch.nn.Linear(512,512,bias=True)\n        self.linear3 = torch.nn.Linear(512,512,bias=True)\n        self.linear4 = torch.nn.Linear(512,512,bias=True)\n        self.linear5 = torch.nn.Linear(512,10,bias=True)\n        self.relu = torch.nn.ReLU()\n        self.dropout = torch.nn.Dropout(p=0.3)\n        \n        self.init_param()\n        \n    def forward(self, x):\n        \n        x = self.relu(self.linear1(x))\n        x = self.dropout(x)\n        x = self.relu(self.linear2(x))\n        x = self.dropout(x)\n        x = self.relu(self.linear3(x))\n        x = self.dropout(x)\n        x = self.relu(self.linear4(x))\n        x = self.dropout(x)\n        x = self.linear5(x)\n        \n        return x\n    \n    def init_param(self) :\n        torch.nn.init.xavier_uniform_(self.linear1.weight)\n        self.linear1.bias.data.fill_(0.01)\n        torch.nn.init.xavier_uniform_(self.linear2.weight)\n        self.linear2.bias.data.fill_(0.01)\n        torch.nn.init.xavier_uniform_(self.linear3.weight)\n        self.linear3.bias.data.fill_(0.01)\n        torch.nn.init.xavier_uniform_(self.linear4.weight)\n        self.linear4.bias.data.fill_(0.01)\n        torch.nn.init.xavier_uniform_(self.linear5.weight)\n        self.linear5.bias.data.fill_(0.01)","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:03.379811Z","iopub.execute_input":"2021-10-15T02:35:03.380432Z","iopub.status.idle":"2021-10-15T02:35:03.392726Z","shell.execute_reply.started":"2021-10-15T02:35:03.380393Z","shell.execute_reply":"2021-10-15T02:35:03.391787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils.data import DataLoader, TensorDataset\n\nbatch_size = 100\nlearning_rate = 0.001\nn_epochs = 15\n\ntrain_dataset = TensorDataset(x_train, y_train)\ntrain_loader = DataLoader(train_dataset, batch_size=batch_size)","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:03.395590Z","iopub.execute_input":"2021-10-15T02:35:03.395857Z","iopub.status.idle":"2021-10-15T02:35:03.407758Z","shell.execute_reply.started":"2021-10-15T02:35:03.395834Z","shell.execute_reply":"2021-10-15T02:35:03.406977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"MNIST_model = MNSIT_DNN_Model().to(device)\noptimizer = torch.optim.Adam(MNIST_model.parameters(), lr=learning_rate)\nloss = torch.nn.CrossEntropyLoss().to(device)","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:03.410753Z","iopub.execute_input":"2021-10-15T02:35:03.411280Z","iopub.status.idle":"2021-10-15T02:35:07.440798Z","shell.execute_reply.started":"2021-10-15T02:35:03.411233Z","shell.execute_reply":"2021-10-15T02:35:07.439962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"total_batch = len(train_loader)\n\nMNIST_model.train()\n\nfor epoch in range(n_epochs):\n    \n    avg_cost = 0\n    \n    for x_train_batch, y_train_batch in train_loader:\n        \n        optimizer.zero_grad()\n        \n        x_train_batch = x_train_batch.to(device)\n        y_train_batch = y_train_batch.to(device)\n\n        y_train_pred = MNIST_model(x_train_batch)\n        \n        cost = loss(y_train_pred,y_train_batch)\n        cost.backward()\n        \n        optimizer.step()\n        \n        avg_cost += cost / total_batch\n        \n    print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))\n\nprint('Learning finished')","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:07.443189Z","iopub.execute_input":"2021-10-15T02:35:07.443464Z","iopub.status.idle":"2021-10-15T02:35:43.756931Z","shell.execute_reply.started":"2021-10-15T02:35:07.443438Z","shell.execute_reply":"2021-10-15T02:35:43.756019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with torch.no_grad():\n    MNIST_model.eval()\n    \n    x_test = x_test.to(device)\n    y_test_pred = MNIST_model(x_test)\n    y_test_pred = torch.argmax(y_test_pred,1)","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:43.758184Z","iopub.execute_input":"2021-10-15T02:35:43.758680Z","iopub.status.idle":"2021-10-15T02:35:43.774800Z","shell.execute_reply.started":"2021-10-15T02:35:43.758642Z","shell.execute_reply":"2021-10-15T02:35:43.773990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test_pred = y_test_pred.cpu().numpy()","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:43.776058Z","iopub.execute_input":"2021-10-15T02:35:43.776425Z","iopub.status.idle":"2021-10-15T02:35:43.781400Z","shell.execute_reply.started":"2021-10-15T02:35:43.776388Z","shell.execute_reply":"2021-10-15T02:35:43.780317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit = pd.read_csv(\"/kaggle/input/2021-ai-w7-p1/submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:43.782704Z","iopub.execute_input":"2021-10-15T02:35:43.783171Z","iopub.status.idle":"2021-10-15T02:35:43.801439Z","shell.execute_reply.started":"2021-10-15T02:35:43.783136Z","shell.execute_reply":"2021-10-15T02:35:43.800657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit['Label'] = y_test_pred\nsubmit","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:43.802478Z","iopub.execute_input":"2021-10-15T02:35:43.802815Z","iopub.status.idle":"2021-10-15T02:35:43.819513Z","shell.execute_reply.started":"2021-10-15T02:35:43.802774Z","shell.execute_reply":"2021-10-15T02:35:43.818598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit.to_csv('./DNN_MNIST_prediction.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2021-10-15T02:35:43.820669Z","iopub.execute_input":"2021-10-15T02:35:43.821212Z","iopub.status.idle":"2021-10-15T02:35:43.843464Z","shell.execute_reply.started":"2021-10-15T02:35:43.821175Z","shell.execute_reply":"2021-10-15T02:35:43.842781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}