{"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)\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.\nfrom sklearn.model_selection import train_test_split","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\nfrom torch.utils.data import DataLoader","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# descargando datos de entrenamiento\ntrain = pd.read_csv(r\"../input/digit-recognizer/train.csv\",dtype = np.float32)\n# se dividen los datos en caracteristicas y etiquetas \ntargets_numpy = train.label.values\nfeatures_numpy = train.loc[:,train.columns != \"label\"].values/255 # normalization\n\n# picamos el set entranamiento con la finalidad de tener un nuvo set de validacion (80%, 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#creamos funciones y tagets tensor para el set de entrenamiento y el de validacion\n#con la finalidad de accumular los gradieantes.\nfeaturesTrain = torch.from_numpy(features_train)\ntargetsTrain = torch.from_numpy(targets_train).type(torch.LongTensor) # data type is long\n\nfeaturesTest = torch.from_numpy(features_test)\ntargetsTest = torch.from_numpy(targets_test).type(torch.LongTensor) # data type is long\n\n\n# vizualizamos una imagen del set\nplt.imshow(features_numpy[22].reshape(28,28))\nplt.axis(\"off\")\nplt.title(str(targets_numpy[22]))\nplt.savefig('graph.png')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Creando modelo CNN\nclass 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=16, kernel_size=4, stride=2, padding=2)\n        self.drop1=nn.Dropout(.3)\n        self.relu1 = nn.ReLU()\n        \n         # Convolution 2\n        self.cnn2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=4, stride=1, padding=2)\n        self.relu2 = nn.ReLU()\n        \n        # Max pool 1\n        self.maxpool1 = nn.MaxPool2d(kernel_size=2)\n     \n        # Convolution 3\n        self.cnn3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=2)\n        self.drop2=nn.Dropout(.15)\n        self.relu3 = nn.ReLU()\n        \n        # Convolution 4\n        self.cnn4 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1)\n        self.relu4 = nn.ReLU()\n        \n        \n        # Max pool 2\n        self.maxpool2 = nn.MaxPool2d(kernel_size=2)\n        \n         # Convolution 5\n        self.cnn5 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=2, stride=1, padding=1)\n        self.drop3=nn.Dropout(.1)\n        self.relu5 = nn.ReLU()\n        \n        \n        # Max pool 3\n        self.maxpool3 = nn.MaxPool2d(kernel_size=2)\n        \n        # Convolution 6\n        self.cnn6 = nn.Conv2d(in_channels=256, out_channels=64, kernel_size=1, stride=1, padding=0)\n        self.relu6 = nn.ReLU()\n        \n        \n        # Fully connected 1\n        self.fc1 = nn.Linear(64, 10) \n    \n    def forward(self, x):\n        # Convolution 1\n        out = self.cnn1(x)\n        out=self.drop1(out)\n        out = self.relu1(out)\n        \n        # Convolution 2\n        out = self.cnn2(out)\n        out = self.relu2(out)\n        \n        # Max pool 1\n        out = self.maxpool1(out)\n        \n        # Convolution 3\n        out = self.cnn3(out)\n        out = self.drop2(out)\n        out = self.relu3(out)\n        \n        # Convolution 4 \n        out = self.cnn4(out)\n        out = self.relu4(out)\n        \n        # Max pool 2 \n        out = self.maxpool2(out)\n        \n        # Convolution 5\n        out = self.drop3(out)\n        out = self.cnn5(out)\n        out = self.relu5(out)\n        \n        # Max pool 3 \n        out = self.maxpool3(out)\n        \n        # Convolution 6 \n        out = self.cnn6(out)\n        out = self.relu6(out)\n\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# tamano de lote, cantidadmde iteraciones\nbatch_size = 120\nn_iters = 2000\nnum_epochs = n_iters / (len(features_train) / batch_size)\nnum_epochs = int(num_epochs)\n\n# Pytorch set de entrenamiento y validacion\ntrain = torch.utils.data.TensorDataset(featuresTrain,targetsTrain)\ntest = torch.utils.data.TensorDataset(featuresTest,targetsTest)\n\n# cargador de datos\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    \n# creando el modelo CNN\nmodel = CNNModel()\n\n# perdida \nerror = nn.CrossEntropyLoss()\n\n# Optimizador ADAM\nlearning_rate = 98e-5\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# modelo entrenamiento\ncount = 0\nloss_list = []\nloss_list1 = []\niteration_list = []\naccuracy_list = []\naccuracy_list1 = []\nfor epoch in range(num_epochs):\n    correcto1=0\n    total1= 0\n    for i, (images, labels) in enumerate(train_loader):\n        \n        train = Variable(images.view(120,1,28,28))\n        labels = Variable(labels)\n        \n        # Gradiante\n        optimizer.zero_grad()\n        \n        # Forward propagation\n        outputs = model(train)\n        # calculando salida del softmax y del loss\n        loss = error(outputs, labels)\n        # calculando gradiantes\n        loss.backward()\n        # actualizando parametros\n        optimizer.step()\n        predicted1 = torch.max(outputs.data, 1)[1]\n        total1 += len(labels)\n        correcto1 += (predicted1 == labels).sum()\n        accuracy1 = 100 * correcto1 / float(total1)\n        count += 1\n        if count % 10 == 0:\n            # Calculando el Accuracy         \n            correct = 0\n            total = 0\n            # iterando en el set de validacion\n            for images, labels in test_loader:\n                \n                test = Variable(images.view(120,1,28,28))\n                labels = Variable(labels)\n                # Forward propagation\n                outputs = model(test)\n                loss1 = error(outputs, labels)\n                # obteniendo una prediccion\n                predicted = torch.max(outputs.data, 1)[1]\n                \n                # sumando uno al numero de etiquetas\n                total += len(labels)\n                \n                correct += (predicted == labels).sum()\n             \n            accuracy = 100 * correct / float(total)\n            \n            # guardando la iteracion de la perdida\n            loss_list.append(loss.data)\n            loss_list1.append(loss1.data)\n            iteration_list.append(count)\n            accuracy_list.append(accuracy)\n            accuracy_list1.append(accuracy1)\n            if count % 20 == 0:\n                # imprimiendo\n                print('Iteration: {}  Loss: {}  Accuracy train: {} Accuracy test: {} %'.format(count, loss.data, accuracy, accuracy1))\n            \n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# grafica loss \nplt.plot(iteration_list,loss_list1,color = \"blue\")\nplt.plot(iteration_list,loss_list,color = \"red\")\nplt.xlabel(\"Number of iteration\")\nplt.ylabel(\"Loss\")\nplt.title(\"CNN: Loss test=red train=blue vs Number of iteration\")\nplt.show()\n\n# gafica accuracy \nplt.plot(iteration_list,accuracy_list,color = \"blue\")\nplt.plot(iteration_list,accuracy_list1,color = \"red\")\nplt.xlabel(\"Number of iteration\")\nplt.ylabel(\"Accuracy\")\nplt.title(\"CNN: Accuracy test=red train=blue vs Number of iteration\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torchvision.transforms as transforms\nfrom   PIL import Image\ntransform = transforms.Compose([\n        transforms.ToTensor(),\n        transforms.Normalize((0.5,), (0.5,))\n    ])\n\n# Get the device we're training on\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef get_digits(df):\n    \"\"\"Loads images as PyTorch tensors\"\"\"\n    # Load the labels if they exist \n    # (they wont for the testing data)\n    labels = []\n    start_inx = 0\n    if 'label' in df.columns:\n        labels = [v for v in df.label.values]\n        start_inx = 1\n        \n    # Load the digit information\n    digits = []\n    for i in range(df.pixel0.size):\n        digit = df.iloc[i].astype(float).values[start_inx:]\n        digit = np.reshape(digit, (28,28))\n        digit = transform(digit).type('torch.FloatTensor')\n        if len(labels) > 0:\n            digits.append([digit, labels[i]])\n        else:\n            digits.append(digit)\n\n    return digits","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define the test data loader\nkag        = pd.read_csv(\"../input/digit-recognizer/test.csv\")\nkagg = pd.read_csv(r\"../input/digit-recognizer/test.csv\",dtype = np.float32)\nkaggg = kagg.loc[:,kagg.columns != \"label\"].values/255 # normalization\ntest_X      = get_digits(kag)\ntest_loader = torch.utils.data.DataLoader(test_X, batch_size=batch_size, shuffle = False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Create storage objects\nImageId, Label = [],[]\n\n# Loop through the data and get the predictions\nfor data in test_loader:\n    # Move tensors to GPU if CUDA is available\n    data = data.to(device)\n    # Make the predictions\n    output = model(data)\n    # Get the most likely predicted digit\n    _, pred = torch.max(output, 1)\n    \n    for i in range(len(pred)):        \n        ImageId.append(len(ImageId)+1)\n        Label.append(pred[i].cpu().numpy())\n\nsub = pd.DataFrame(data={'ImageId':ImageId, 'Label':Label})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.to_csv(\"submission.csv\", index=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(kaggg[1255].reshape(28,28))\nplt.axis(\"off\")\nplt.title(str(Label[1255]))\nplt.savefig('graph.png')\nplt.show()\n","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}