{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.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":3004,"databundleVersionId":861823,"sourceType":"competition"},{"sourceId":4631096,"sourceType":"datasetVersion","datasetId":2694461},{"sourceId":4631176,"sourceType":"datasetVersion","datasetId":2694509},{"sourceId":4631193,"sourceType":"datasetVersion","datasetId":2694525}],"dockerImageVersionId":30302,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"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\nimport numpy as np","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-10-16T15:26:14.191630Z","iopub.execute_input":"2023-10-16T15:26:14.192671Z","iopub.status.idle":"2023-10-16T15:26:17.008286Z","shell.execute_reply.started":"2023-10-16T15:26:14.192566Z","shell.execute_reply":"2023-10-16T15:26:17.005111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Prepare Dataset\n# load data\ntrain = pd.read_csv(r\"/kaggle/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)","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:26:17.010336Z","iopub.execute_input":"2023-10-16T15:26:17.010865Z","iopub.status.idle":"2023-10-16T15:26:22.262332Z","shell.execute_reply.started":"2023-10-16T15:26:17.010828Z","shell.execute_reply":"2023-10-16T15:26:22.261356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features_numpy[10].shape","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:26:22.263604Z","iopub.execute_input":"2023-10-16T15:26:22.264600Z","iopub.status.idle":"2023-10-16T15:26:22.274007Z","shell.execute_reply.started":"2023-10-16T15:26:22.264563Z","shell.execute_reply":"2023-10-16T15:26:22.272952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:26:22.276724Z","iopub.execute_input":"2023-10-16T15:26:22.278070Z","iopub.status.idle":"2023-10-16T15:26:22.417250Z","shell.execute_reply.started":"2023-10-16T15:26:22.278035Z","shell.execute_reply":"2023-10-16T15:26:22.416149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# device = torch.device(\"cuda:0\")","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:26:22.418606Z","iopub.execute_input":"2023-10-16T15:26:22.419201Z","iopub.status.idle":"2023-10-16T15:26:22.425051Z","shell.execute_reply.started":"2023-10-16T15:26:22.419166Z","shell.execute_reply":"2023-10-16T15:26:22.423817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create Logistic Regression Model\nclass LogisticRegressionModel(nn.Module):\n    def __init__(self, input_dim, output_dim):\n        super(LogisticRegressionModel, self).__init__()\n        # Linear part\n        self.linear = nn.Linear(input_dim, output_dim)\n        \n        # There should be logistic function right?\n        # However logistic function in pytorch is in loss function\n        # So actually we do not forget to put it, it is only at next parts\n    \n    def forward(self, x):\n        out = self.linear(x)\n        return out\n\n# Instantiate Model Class\ninput_dim = 28*28 # size of image px*px\noutput_dim = 10  # labels 0,1,2,3,4,5,6,7,8,9\n\n# create logistic regression model\nmodel = LogisticRegressionModel(input_dim, output_dim)\n# model.to(device)\n\n# Cross Entropy Loss  \nerror = nn.CrossEntropyLoss()\n\n# SGD Optimizer \nlearning_rate = 0.001\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:26:22.426674Z","iopub.execute_input":"2023-10-16T15:26:22.427108Z","iopub.status.idle":"2023-10-16T15:26:22.439481Z","shell.execute_reply.started":"2023-10-16T15:26:22.427075Z","shell.execute_reply":"2023-10-16T15:26:22.438239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_epochs = 200","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:26:22.440683Z","iopub.execute_input":"2023-10-16T15:26:22.441466Z","iopub.status.idle":"2023-10-16T15:26:22.447811Z","shell.execute_reply.started":"2023-10-16T15:26:22.441427Z","shell.execute_reply":"2023-10-16T15:26:22.446366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(features_train) / batch_size","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:26:22.449206Z","iopub.execute_input":"2023-10-16T15:26:22.449605Z","iopub.status.idle":"2023-10-16T15:26:22.462467Z","shell.execute_reply.started":"2023-10-16T15:26:22.449572Z","shell.execute_reply":"2023-10-16T15:26:22.461268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features_numpy.__len__()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:26:22.463902Z","iopub.execute_input":"2023-10-16T15:26:22.464348Z","iopub.status.idle":"2023-10-16T15:26:22.475963Z","shell.execute_reply.started":"2023-10-16T15:26:22.464313Z","shell.execute_reply":"2023-10-16T15:26:22.474571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Traning the Model\n\nloss_list = []\niteration_list = []\ncount = 0\nfor epoch in range(num_epochs):\n    for i, (images, labels) in enumerate(train_loader):\n        \n        # Define variables\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 cross entropy loss\n        loss = error(outputs, labels)\n        \n        # Calculate gradients\n        loss.backward()\n        \n        # Update parameters\n        optimizer.step()\n        \n        \n        # Prediction\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                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        \n        count += 1\n\n        if count % 500 == 0:\n            # Print Loss\n            print('Iteration: {}  Loss: {}  Accuracy: {}%'.format(count, loss.data, accuracy))","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:26:22.480380Z","iopub.execute_input":"2023-10-16T15:26:22.480978Z","iopub.status.idle":"2023-10-16T15:29:26.406713Z","shell.execute_reply.started":"2023-10-16T15:26:22.480934Z","shell.execute_reply":"2023-10-16T15:29:26.405740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for index, (images, labels) in enumerate(test_loader): \n    test = Variable(images.view(-1, 28*28))\n    \n    if index==20:\n        break\ntest[0].shape","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:29:26.407987Z","iopub.execute_input":"2023-10-16T15:29:26.408578Z","iopub.status.idle":"2023-10-16T15:29:26.432949Z","shell.execute_reply.started":"2023-10-16T15:29:26.408540Z","shell.execute_reply":"2023-10-16T15:29:26.431719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# visualize one of the images in data set\nplt.imshow(test[-1].reshape(28,28))\nplt.axis(\"off\")\nplt.title(\"fddfdsf\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:46:52.542348Z","iopub.execute_input":"2023-10-16T15:46:52.542776Z","iopub.status.idle":"2023-10-16T15:46:52.782629Z","shell.execute_reply.started":"2023-10-16T15:46:52.542743Z","shell.execute_reply":"2023-10-16T15:46:52.781445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!wget https://i.ytimg.com/vi/8LeZI3ptwG0/maxresdefault.jpg","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:29:26.541152Z","iopub.execute_input":"2023-10-16T15:29:26.542109Z","iopub.status.idle":"2023-10-16T15:29:27.755138Z","shell.execute_reply.started":"2023-10-16T15:29:26.542058Z","shell.execute_reply":"2023-10-16T15:29:27.753824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\ndata = cv2.imread(\"maxresdefault.jpg\")\ndata = cv2.resize(data, (28, 28))","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:29:27.757119Z","iopub.execute_input":"2023-10-16T15:29:27.757416Z","iopub.status.idle":"2023-10-16T15:29:27.971510Z","shell.execute_reply.started":"2023-10-16T15:29:27.757386Z","shell.execute_reply":"2023-10-16T15:29:27.970465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = 255 - data","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:29:27.972933Z","iopub.execute_input":"2023-10-16T15:29:27.973320Z","iopub.status.idle":"2023-10-16T15:29:27.978431Z","shell.execute_reply.started":"2023-10-16T15:29:27.973276Z","shell.execute_reply":"2023-10-16T15:29:27.977387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = data/255","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:29:27.979873Z","iopub.execute_input":"2023-10-16T15:29:27.980735Z","iopub.status.idle":"2023-10-16T15:29:27.991273Z","shell.execute_reply.started":"2023-10-16T15:29:27.980700Z","shell.execute_reply":"2023-10-16T15:29:27.990060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.shape","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:29:27.993180Z","iopub.execute_input":"2023-10-16T15:29:27.993976Z","iopub.status.idle":"2023-10-16T15:29:28.006144Z","shell.execute_reply.started":"2023-10-16T15:29:27.993882Z","shell.execute_reply":"2023-10-16T15:29:28.004578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"b, g, r = cv2.split(data) # For BGR image","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:29:28.008668Z","iopub.execute_input":"2023-10-16T15:29:28.009478Z","iopub.status.idle":"2023-10-16T15:29:28.019248Z","shell.execute_reply.started":"2023-10-16T15:29:28.009438Z","shell.execute_reply":"2023-10-16T15:29:28.018092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = Variable(torch.Tensor(list(b)).view(-1, 28*28))\noutputs = model(test)\npredicted = torch.max(outputs.data, 1)[1]","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:29:28.020916Z","iopub.execute_input":"2023-10-16T15:29:28.022311Z","iopub.status.idle":"2023-10-16T15:29:28.033174Z","shell.execute_reply.started":"2023-10-16T15:29:28.022269Z","shell.execute_reply":"2023-10-16T15:29:28.031821Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predicted","metadata":{"execution":{"iopub.status.busy":"2023-10-16T15:29:28.034836Z","iopub.execute_input":"2023-10-16T15:29:28.036094Z","iopub.status.idle":"2023-10-16T15:29:28.044823Z","shell.execute_reply.started":"2023-10-16T15:29:28.036049Z","shell.execute_reply":"2023-10-16T15:29:28.043591Z"},"trusted":true},"execution_count":null,"outputs":[]}]}