{"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data\nfrom torch.autograd import Variable\nfrom sklearn.model_selection import train_test_split\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# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Obtención del dataset de train.csv","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")\nprint(train.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Obtención del training set para entrenar el modelo","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"y = train['label'].values\nx = train.drop(['label'],1).values \n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.15)\nprint(x_train.shape)\nprint(x_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualización de una imagen random del train dataset x_train","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\ndef plot_random_digit():\n    random_index = np.random.randint(0,x_train.shape[0])\n    plt.imshow(x_train[random_index].reshape((28,28)), cmap='nipy_spectral')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_random_digit()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Procesamiento de datos","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 32\n\ntorch_x_train = torch.from_numpy(x_train).type(torch.LongTensor)\ntorch_x_train = torch_x_train.view(-1,1,28,28).float()\ntorch_y_train = torch.from_numpy(y_train).type(torch.LongTensor)\n\ntorch_x_test = torch.from_numpy(x_test).type(torch.LongTensor)\ntorch_x_test = torch_x_test.view(-1,1,28,28).float()\ntorch_y_test = torch.from_numpy(y_test).type(torch.LongTensor)\n\ntrain = torch.utils.data.TensorDataset(torch_x_train,torch_y_train)\ntest = torch.utils.data.TensorDataset(torch_x_test,torch_y_test)\n\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\nprint(torch_x_train.shape)\nprint(torch_x_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Modelo CNN","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"class CNN(nn.Module):\n    def __init__(self):\n        super(CNN, self).__init__()\n        self.conv1 = nn.Conv2d(1, 32, kernel_size=5)\n        self.conv2 = nn.Conv2d(32, 32, kernel_size=5)\n        self.conv3 = nn.Conv2d(32, 64, kernel_size=5)\n        self.fc1 = nn.Linear(3*3*64, 256)\n        self.fc2 = nn.Linear(256, 10)\n\n    def forward(self, x):\n        x = F.relu(self.conv1(x))\n        x = F.relu(F.max_pool2d(self.conv2(x), 2))\n        x = F.dropout(x, p=0.5, training=self.training)\n        x = F.relu(F.max_pool2d(self.conv3(x),2))\n        x = F.dropout(x, p=0.5, training=self.training)\n        x = x.view(-1,3*3*64)\n        x = F.relu(self.fc1(x))\n        x = F.dropout(x, training=self.training)\n        x = self.fc2(x)\n        return F.log_softmax(x, dim=1)\n \ncnn = CNN()\nprint(cnn)\n\nit = iter(train_loader)\nX_batch, y_batch = next(it)\nprint(cnn.forward(X_batch).shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Función para entrenar el modelo","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def fit(model, train_loader):\n    optimizer = torch.optim.Adam(model.parameters())\n    criterion = nn.CrossEntropyLoss()\n    epochs = 5\n    model.train()\n    for epoch in range(epochs):\n        correct = 0\n        print('Epoch: {}'.format(epoch))\n        for batch_idx, (x_batch, y_batch) in enumerate(train_loader):\n            var_x_batch = Variable(x_batch).float()\n            var_y_batch = Variable(y_batch)\n            optimizer.zero_grad()\n            output = model(var_x_batch)\n            loss = criterion(output, var_y_batch)\n            loss.backward()\n            optimizer.step()\n            predicted = torch.max(output.data, 1)[1] \n            correct += (predicted == var_y_batch).sum()\n            if batch_idx % 50 == 0:\n                print('({:.0f}%)\\tLoss: {:.6f}\\t Accuracy: {:.3f}%'\n                      .format(100.*batch_idx / len(train_loader),\n                              loss.data, \n                              float(correct*100) / float(batch_size*(batch_idx+1)))\n                     )\n        print('------------------------------------------------------------------------------------')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fit(cnn, train_loader)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Evaluación del modelo ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def evaluate(model):\n    correct = 0\n    for test_imgs, test_labels in test_loader:\n        test_imgs = Variable(test_imgs).float()\n        output = model(test_imgs)\n        predicted = torch.max(output,1)[1]\n        correct += (predicted == test_labels).sum()\n    print(\"Test accuracy: {:.3f}% \".format(100*(float(correct) / (len(test_loader)*batch_size))))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"evaluate(cnn)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Función para ver una imagen y predecir su clase","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def view_classify(img, ps, version=\"MNIST\"):\n    ps = ps.data.numpy().squeeze()\n    fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)\n    ax1.imshow(img.resize_(1, 28, 28).numpy().squeeze())\n    ax1.axis('off')\n    ax2.barh(np.arange(10), ps)\n    ax2.set_aspect(0.1)\n    ax2.set_yticks(np.arange(10))\n    if version == \"MNIST\":\n        ax2.set_yticklabels(np.arange(10))\n   \n    ax2.set_title('Class Probability')\n    ax2.set_xlim(0, 1.1)\n\n    plt.tight_layout()\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predecir una imagen random de la data usada para entrenar el modelo","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"images, labels = next(iter(train_loader))\nrandom_index = np.random.randint(0,images.shape[0])\nimg = images[random_index].view(-1, 1,28,28).float()\n\nwith torch.no_grad():\n    output = cnn(img).cpu()\n\nps = torch.exp(output)\nview_classify(img.view(1, 28, 28), ps)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predicciones usando test.csv","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"raw_test = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")\nprint(raw_test.shape)\nraw_test = raw_test.drop(\"id\",axis=\"columns\") \nprint(raw_test.shape)\nraw_test = raw_test / 255 \ntests = raw_test.values.reshape(-1,28,28,1)\nprint(tests.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"torch_x_test = torch.from_numpy(tests).type(torch.LongTensor)\ntorch_x_test = torch_x_test.view(-1,1,28,28).float()\n\nwith torch.no_grad():\n    output = cnn(torch_x_test).cpu()\n\nsoftmax = torch.exp(output)\nprob = list(softmax.numpy())\npredictions = np.argmax(prob, axis=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Entrega con las predicciones obtenidas de test.csv","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv('../input/Kannada-MNIST/sample_submission.csv')\nsubmission['label'] = predictions\nsubmission.to_csv(\"submission.csv\", index=False)\nsubmission.head()","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}