{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport os\nfrom PIL import Image\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score, roc_curve, roc_auc_score\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Loading Dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/Kannada-MNIST/train.csv\")\ntest = pd.read_csv(\"../input/Kannada-MNIST/test.csv\")\ntrain.head(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head(3)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Feature and Label data"},{"metadata":{"trusted":true},"cell_type":"code","source":"X = train.drop('label', axis=1)\ntest = test\ny = train.label","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Using PyTorch Linear Layer"},{"metadata":{"trusted":true},"cell_type":"code","source":"X = train.iloc[:, 1:].values\ny = train.iloc[:, 0].values\nprint(\"Shape of X is :{} Shape of y is :{}\".format(X.shape, y.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_test, y_train, y_test = train_test_split(X,y, test_size=.1, random_state=42, stratify=y)\nprint(x_train.shape, x_test.shape, y_train.shape, y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = torch.FloatTensor(x_train)\nx_test = torch.FloatTensor(x_test)\ny_train = torch.LongTensor(y_train)\ny_test = torch.LongTensor(y_test)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class Model(nn.Module):\n    def __init__(self, input_features=784, hidden_layer1=392, hidden_layer2=196, output_features=10):\n        super().__init__()\n        self.fc1 = nn.Linear(input_features,hidden_layer1)                  \n        self.fc2 = nn.Linear(hidden_layer1, hidden_layer2)                  \n        self.out = nn.Linear(hidden_layer2, output_features)      \n        \n    def forward(self, x):\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = self.out(x)\n        return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Model = Model()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#optimizer = torch.optim.SGD(Model.parameters(), lr=0.01)\noptimizer = torch.optim.Adam(Model.parameters(), lr=0.001)\n#loss = nn.CrossEntropyLoss()\ncriterion = nn.CrossEntropyLoss()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 100\ntrain_losses = []\nvalid_losses = []\ntrain_correct = []\nvalid_correct = []\n\nfor epoch in range(epochs):\n    out1 = Model.forward(x_train)\n    train_loss = criterion(out1, y_train)\n    train_losses.append(train_loss)\n    \n    out2 = Model.forward(x_test)\n    valid_loss = criterion(out2, y_test)\n    valid_losses.append(valid_loss)\n\n    optimizer.zero_grad()\n    train_loss.backward()\n    valid_loss.backward()\n    optimizer.step()\n    \n    print(f'Epoch: {epoch:2}  Train_loss: {train_loss.item():10.8f}  Valid_loss:{valid_loss.item():10.8f} ')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(range(epochs), train_losses)\nplt.ylabel(\"Loss\")\nplt.xlabel(\"epoch\")\n\nplt.plot(range(epochs), valid_losses)\nplt.ylabel(\"Loss\")\nplt.xlabel(\"epoch\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted = Model(x_test)\n_, predict_y = torch.max(predicted, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('prediction accuracy :', accuracy_score(y_test.data, predict_y.data))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Classification Report\nprint(classification_report(y_test.data, predict_y.data))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Confusion Matrix\ncm = confusion_matrix(y_test, predict_y.data)\nplt.figure(figsize=(7,7))\nsns.heatmap(cm, fmt='.0f', annot=True, linewidths=0.2, linecolor='purple')\nplt.xlabel('predicted value')\nplt.ylabel('Truth value')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.read_csv(\"../input/Kannada-MNIST/sample_submission.csv\") \ntest = pd.read_csv(\"../input/Kannada-MNIST/test.csv\")\nsub.head(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = test.drop('id', axis=1).values\ntest_df = torch.FloatTensor(test_df)\n    \npredicted = Model(test_df)\n_, predict_test = torch.max(predicted, 1)\npredicted_data = predict_test.data\npredicted_data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub['label'] = predicted_data\nsub.to_csv('predicted.csv', index=False) \nsub.head()","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}