{"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 Libraries\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Prepare Dataset\n# load data\ntrain = pd.read_csv(r\"../input/digit-recognizer/train.csv\",dtype = np.float32)\n\n# split data into features(pixels) and labels(numbers from 0 to 9)\ntargets_numpy = train.label.values\nfeatures_numpy = train.loc[:,train.columns != \"label\"].values/255 # normalization\n\n# train test split. Size of train data is 80% and size of test data is 20%. \nfeatures_train, features_test, targets_train, targets_test = train_test_split(features_numpy,\n                                                                             targets_numpy,\n                                                                             test_size = 0.2,\n                                                                             random_state = 42) \n\n# create feature and targets tensor for train set. As you remember we need variable to accumulate gradients. Therefore first we create tensor, then we will create variable\nfeaturesTrain = torch.from_numpy(features_train)\ntargetsTrain = torch.from_numpy(targets_train).type(torch.LongTensor) # data type is long\n\n# create feature and targets tensor for test set.\nfeaturesTest = torch.from_numpy(features_test)\ntargetsTest = torch.from_numpy(targets_test).type(torch.LongTensor) # data type is long\n\n# batch_size, epoch and iteration\nbatch_size = 100\nn_iters = 10000\nnum_epochs = n_iters / (len(features_train) / batch_size)\nnum_epochs = int(num_epochs)\n\n# Pytorch train and test sets\ntrain = torch.utils.data.TensorDataset(featuresTrain,targetsTrain)\ntest = torch.utils.data.TensorDataset(featuresTest,targetsTest)\n\n# data loader\ntrain_loader = DataLoader(train, batch_size = batch_size, shuffle = False)\ntest_loader = DataLoader(test, batch_size = batch_size, shuffle = False)\n\n# visualize one of the images in data set\nplt.imshow(features_numpy[10].reshape(28,28))\nplt.axis(\"off\")\nplt.title(str(targets_numpy[10]))\nplt.savefig('graph.png')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class LogisticRegressionModel(nn.Module):\n    def __init__ (self, input_dim, output_dim):\n        super(LogisticRegressionModel, self).__init__() #Inherit the Neural Network Model\n        self.linear= nn.Linear(input_dim, output_dim)\n    def forward(self,x): #forward metodu pytorch tarafından otomatik olarak çağrılır.\n        out=self.linear(x)\n        return out\n\ninput_dim= 28*28\noutput_dim= 10\n\nmodel= LogisticRegressionModel(input_dim, output_dim)\n\nerror= nn.CrossEntropyLoss()\n\nlearning_rate=0.001\noptimizer= torch.optim.SGD(model.parameters(), learning_rate)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Training the Model\ncount=0\nloss_list=[]\niteration_list=[]\nfor epoch in range(num_epochs):\n    for i, (images, labels) in enumerate(train_loader): #data loader bana iki tane değer return ediyor. Tuple ve index sayısı\n        #tuple içinde resimler ve karşılık gelen labellar var.\n        \n        #Define variables\n        train= Variable(images.view(-1,28*28)) #gradient hesabı yapıyorum ve bu gradientleri tutması için variable lara ihtiyaç var.        \n        #view metodu numpy daki reshape metoduna karşılık geliyor.\n        labels=Variable(labels)\n        \n        #Clear gradients\n        optimizer.zero_grad()\n        \n        #Forward propagation\n        outputs=model(train) #modeli çağırdığımda forward metodunu da otomatik olarak çağırmış oluyorum.\n        \n        #calculate softmax and cross entropy loss Softmax fonksiyonu bunun içerisinde\n        loss=error(outputs, labels)\n        \n        #calculate gradients\n        loss.backward()\n      \n        #update parameters\n        optimizer.step() #modelin parametreleri optimizer ın içerisinde. \n        \n        count += 1\n        #prediction #50 adımda bir test ediyorum.\n        if count%50 ==0:\n            #calculate acc\n            correct=0\n            total=0\n            #predict test dataset\n            for images, labels in test_loader:\n                test= Variable(images.view(-1,28*28))\n                \n                #Forward propagation\n                outputs= model(test)\n                \n                #get predictions from the maximum value\n                predicted= torch.max(outputs.data,1)[1]\n                \n                #Total number of labels\n                total+=len(labels)\n                \n                #Total correction predictions\n                correct+= (predicted==labels).sum()\n                \n            accuracy=100 * correct / float(total)\n            # store loss and iteration \n            loss_list.append(loss.data)\n            iteration_list.append(count)\n        if count%500 ==0:\n            #Print loss\n            print(\"Iteration: {} Loss: {} Accuracy: {}%\".format(count, loss.data, accuracy))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#visualization\nplt.plot(iteration_list, loss_list)\nplt.xlabel(\"Number of iteration\")\nplt.ylabel(\"Loss\")\nplt.title(\"Logistic Regression: Loss vs Number of iteration\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Import Libraries\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Create ANN Model\nclass ANNModel(nn.Module):\n    \n    def __init__(self, input_dim, hidden_dim, output_dim):\n        super(ANNModel, self).__init__()\n        \n        # Linear function 1: 784 --> 150\n        self.fc1 = nn.Linear(input_dim, hidden_dim) \n        # Non-linearity 1\n        self.relu1 = nn.ReLU()\n        \n        # Linear function 2: 150 --> 150\n        self.fc2 = nn.Linear(hidden_dim, hidden_dim)\n        # Non-linearity 2\n        self.tanh2 = nn.Tanh()\n        \n        # Linear function 3: 150 --> 150\n        self.fc3 = nn.Linear(hidden_dim, hidden_dim)\n        # Non-linearity 3\n        self.elu3 = nn.ELU()\n        \n        # Linear function 4 (readout): 150 --> 10\n        self.fc4 = nn.Linear(hidden_dim, output_dim)  \n    \n    def forward(self, x):\n        # Linear function 1\n        out = self.fc1(x)\n        # Non-linearity 1\n        out = self.relu1(out)\n        \n        # Linear function 2\n        out = self.fc2(out)\n        # Non-linearity 2\n        out = self.tanh2(out)\n        \n        # Linear function 2\n        out = self.fc3(out)\n        # Non-linearity 2\n        out = self.elu3(out)\n        \n        # Linear function 4 (readout)\n        out = self.fc4(out)\n        return out\n\n# instantiate ANN\ninput_dim = 28*28\nhidden_dim = 150 #hidden layer dim is one of the hyper parameter and it should be chosen and tuned. For now I only say 150 there is no reason.\noutput_dim = 10\n\n# Create ANN\nmodel = ANNModel(input_dim, hidden_dim, output_dim)\n\n# Cross Entropy Loss \nerror = nn.CrossEntropyLoss()\n\n# SGD Optimizer\nlearning_rate = 0.02\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(type(outputs))\nprint(type(labels))\nprint(type(featuresTrain))\nprint(type(targetsTrain))\nprint(type(featuresTest))\nprint(type(targetsTest))\nprint(type(train))\nprint(type(test))\nprint(type(labels))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# ANN model training\ncount = 0\nloss_list = []\niteration_list = []\naccuracy_list = []\nfor epoch in range(num_epochs):\n    for i, (images, labels) in enumerate(train_loader):\n\n        train = Variable(images.view(-1, 28*28))\n        labels = Variable(labels)\n        \n        # Clear gradients\n        optimizer.zero_grad()\n        \n        # Forward propagation\n        outputs = model(train)\n        \n        # Calculate softmax and ross entropy loss\n        loss = error(outputs, labels)\n        \n        # Calculating gradients\n        loss.backward()\n        \n        # Update parameters\n        optimizer.step()\n        \n        count += 1\n        \n        if count % 50 == 0:\n            # Calculate Accuracy         \n            correct = 0\n            total = 0\n            # Predict test dataset\n            for images, labels in test_loader:\n\n                test = Variable(images.view(-1, 28*28))\n                \n                # Forward propagation\n                outputs = model(test)\n                \n                # Get predictions from the maximum value\n                predicted = torch.max(outputs.data, 1)[1]\n                \n                # Total number of labels\n                total += len(labels)\n\n                # Total correct predictions\n                correct += (predicted == labels).sum()\n            \n            accuracy = 100 * correct / float(total)\n            \n            # store loss and iteration\n            loss_list.append(loss.data)\n            iteration_list.append(count)\n            accuracy_list.append(accuracy)\n        if count % 500 == 0:\n            # Print Loss\n            print('Iteration: {}  Loss: {}  Accuracy: {} %'.format(count, loss.data, accuracy))","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":4}