{"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"},{"sourceId":11071,"sourceType":"datasetVersion","datasetId":7836}],"dockerImageVersionId":30673,"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 in \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# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-03T09:26:54.603487Z","iopub.execute_input":"2024-04-03T09:26:54.603879Z","iopub.status.idle":"2024-04-03T09:26:55.899769Z","shell.execute_reply.started":"2024-04-03T09:26:54.603849Z","shell.execute_reply":"2024-04-03T09:26:55.897298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import Libraries\nimport torch\nimport cv2\nimport numpy as np\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","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:26:55.902190Z","iopub.execute_input":"2024-04-03T09:26:55.902847Z","iopub.status.idle":"2024-04-03T09:27:01.846342Z","shell.execute_reply.started":"2024-04-03T09:26:55.902811Z","shell.execute_reply":"2024-04-03T09:27:01.845007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## # Prepare Dataset\n# load data\n# train = pd.read_csv(r\"../input/train.csv\",dtype = np.float32)\n\n# split data into features(pixels) and labels(numbers from 0 to 9)\ntargets_numpy = np.load('/kaggle/input/sign-language-digits-dataset/Y.npy')\nfeatures_numpy = np.load('/kaggle/input/sign-language-digits-dataset/X.npy') # normalization\n# train test split. Size of train data is 80% and size of test data is 20%. \n# image_shape=(64,64,1)\n\nnew_y = []\ncount = 0\nfor i in targets_numpy: \n    count = 0\n    for j in i:\n        if j==1:\n            new_y.append(count)\n            break      \n        count += 1\n\nnew_features=[]\nfor i in features_numpy:\n    i = cv2.resize(i, (64,64))\n    new_features.append(i)\n\nfeatures_numpy = np.array(new_features)[:2000]\ntargets_numpy=np.array(new_y)[:2000]\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 = 150\nn_iters = 10001\nnum_epochs = n_iters / (len(features_train) / batch_size)\nnum_epochs = int(num_epochs)\nprint(num_epochs)\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[700].reshape(64,64))\nplt.axis(\"off\")\nprint(targets_numpy[700])\nplt.savefig('graph.png')\nplt.show()\nprint(len(features_numpy))","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:27:01.848191Z","iopub.execute_input":"2024-04-03T09:27:01.848749Z","iopub.status.idle":"2024-04-03T09:27:03.041825Z","shell.execute_reply.started":"2024-04-03T09:27:01.848717Z","shell.execute_reply":"2024-04-03T09:27:03.040284Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"(features_numpy.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:27:03.045410Z","iopub.execute_input":"2024-04-03T09:27:03.046432Z","iopub.status.idle":"2024-04-03T09:27:03.057130Z","shell.execute_reply.started":"2024-04-03T09:27:03.046372Z","shell.execute_reply":"2024-04-03T09:27:03.055482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import Libraries\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:27:08.130369Z","iopub.execute_input":"2024-04-03T09:27:08.131065Z","iopub.status.idle":"2024-04-03T09:27:08.136055Z","shell.execute_reply.started":"2024-04-03T09:27:08.131029Z","shell.execute_reply":"2024-04-03T09:27:08.134682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CNNModel(nn.Module):\n    def __init__(self):\n        super(CNNModel, self).__init__()\n        \n        # Convolution 1\n        self.cnn1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=5, stride=1, padding=0)\n        self.relu1 = nn.ReLU()\n        \n        # Max pool 1\n        self.maxpool1 = nn.MaxPool2d(kernel_size=2)\n     \n        # Convolution 2\n        self.cnn2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=0)\n        self.relu2 = nn.ReLU()\n        \n        # Max pool 2\n        self.maxpool2 = nn.MaxPool2d(kernel_size=2)\n\n        \n        # Fully connected 1\n        self.fc1 = nn.Linear(64 * 13 * 13, 10) \n    \n    def forward(self, x):\n        # Convolution 1\n        out = self.cnn1(x)\n        out = self.relu1(out)\n        \n        # Max pool 1\n        out = self.maxpool1(out)\n        \n        # Convolution 2 \n        out = self.cnn2(out)\n        out = self.relu2(out)\n        \n        # Max pool 2 \n        out = self.maxpool2(out)\n        \n        # flatten\n        out = out.view(out.size(0), -1)\n\n        # Linear function (readout)\n        out = self.fc1(out)\n        \n        return out\n\n# batch_size, epoch and iteration\nbatch_size = 100\nn_iters = 3000\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 = torch.utils.data.DataLoader(train, batch_size = batch_size, shuffle = False)\ntest_loader = torch.utils.data.DataLoader(test, batch_size = batch_size, shuffle = False)\n    \n# Create CNN\nmodel = CNNModel()\n\n# Cross Entropy Loss \nerror = nn.CrossEntropyLoss()\n\n# SGD Optimizer\nlearning_rate = 0.2\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:43:08.487396Z","iopub.execute_input":"2024-04-03T09:43:08.487886Z","iopub.status.idle":"2024-04-03T09:43:08.508360Z","shell.execute_reply.started":"2024-04-03T09:43:08.487849Z","shell.execute_reply":"2024-04-03T09:43:08.506894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# CNN 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(100,1,64,64))\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            # Iterate through test dataset\n            for images, labels in test_loader:\n                \n                test = Variable(images.view(100,1,64,64))\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                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))","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:43:10.026680Z","iopub.execute_input":"2024-04-03T09:43:10.027112Z","iopub.status.idle":"2024-04-03T10:01:38.737631Z","shell.execute_reply.started":"2024-04-03T09:43:10.027081Z","shell.execute_reply":"2024-04-03T10:01:38.736337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import ConfusionMatrixDisplay","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:34:39.241765Z","iopub.status.idle":"2024-04-03T09:34:39.242639Z","shell.execute_reply.started":"2024-04-03T09:34:39.242426Z","shell.execute_reply":"2024-04-03T09:34:39.242446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_predicted=[]\nlabel_true=[]\nfor images, labels in test_loader:\n                \n    test = Variable(images.view(100,1,64,64))\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    label_true.extend(labels)\n    label_predicted.extend(predicted)","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:34:39.244351Z","iopub.status.idle":"2024-04-03T09:34:39.245201Z","shell.execute_reply.started":"2024-04-03T09:34:39.244991Z","shell.execute_reply":"2024-04-03T09:34:39.245011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cm = confusion_matrix(label_true, label_predicted)","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:34:39.246675Z","iopub.status.idle":"2024-04-03T09:34:39.247064Z","shell.execute_reply.started":"2024-04-03T09:34:39.246876Z","shell.execute_reply":"2024-04-03T09:34:39.246893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ConfusionMatrixDisplay(cm).plot()","metadata":{"execution":{"iopub.status.busy":"2024-04-03T09:34:39.249057Z","iopub.status.idle":"2024-04-03T09:34:39.249488Z","shell.execute_reply.started":"2024-04-03T09:34:39.249290Z","shell.execute_reply":"2024-04-03T09:34:39.249308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}