{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import torch\nimport torchvision\nfrom torchvision import transforms, datasets\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tqdm\nfrom numpy import genfromtxt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data = genfromtxt('/kaggle/input/Kannada-MNIST/train.csv', delimiter=',')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data = genfromtxt('/kaggle/input/Kannada-MNIST/test.csv', delimiter=',')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data = train_data[1:]\ntest_data =test_data[1:]\ntrain = []\ntest = []","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(train_data)):\n    train.append((torch.tensor(train_data[i][1:], dtype=torch.float64).reshape(1,28,28) , int(train_data[i][0])))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trainset = torch.utils.data.DataLoader(train, batch_size=10, shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class Net(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.fc1 = nn.Linear(28*28, 64)\n        self.fc2 = nn.Linear(64, 64)\n        self.fc3 = nn.Linear(64, 64)\n        self.fc4 = nn.Linear(64, 10)\n\n    def forward(self, x):\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = F.relu(self.fc3(x))\n        x = self.fc4(x)\n        return F.log_softmax(x, dim=1)\n\nnet = Net()\nprint(net)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch.optim as optim","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss_function = nn.CrossEntropyLoss()\noptimizer = optim.Adam(net.parameters(), lr=0.001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for epoch in range(10): # 3 full passes over the data\n    for data in trainset:  # `data` is a batch of data\n        X, y = data  # X is the batch of features, y is the batch of targets.\n        net.zero_grad()  # sets gradients to 0 before loss calc. You will do this likely every step.\n        output = net(X.float().view(-1,784))  # pass in the reshaped batch (recall they are 28x28 atm)\n        loss = F.nll_loss(output, y)  # calc and grab the loss value\n        loss.backward()  # apply this loss backwards thru the network's parameters\n        optimizer.step()  # attempt to optimize weights to account for loss/gradients\n    print(loss)  # print loss. We hope loss (a measure of wrong-ness) declines! ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(test_data)):\n    test.append((torch.tensor(test_data[i][1:], dtype=torch.float64).reshape(1,28,28) , int(test_data[i][0])))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with torch.no_grad():\n    for data in test[:100]:\n        X, y = data\n        output = net(X.float().view(-1,784))\n        #print(output)\n        for i in output:\n            print(y, ':', int(torch.argmax(i)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# write file\nf = open('output.csv', 'w+')\nf.write('id,label\\n')\n\nwith torch.no_grad():\n    for data in test:\n        X, y = data\n        output = net(X.float().view(-1,784))\n        #print(output)\n        for i in output:\n            #print(y, ':', int(torch.argmax(i)))\n            txt = '{},{}\\n'.format(int(y), int(torch.argmax(i)))\n            f.write(txt)\n            \nf.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":1}