{"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)\n\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.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# importar libreria"},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd #para leer el dataset en un dataframe\nimport numpy as np #para calculos de algebra\n#librerias para graficas\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n%matplotlib inline\n\n\nfrom sklearn.model_selection import train_test_split #libreria de prepocesamiento de datos\nfrom sklearn.metrics import confusion_matrix #libreria imprimir la matriz de confusion\nfrom sklearn.metrics import roc_auc_score\nimport itertools\nfrom keras.utils import np_utils\n\nfrom matplotlib import pyplot #Graficar el Data Augmentation\n\nfrom keras.utils.np_utils import to_categorical # libreria para el one hot encoding\n\n#librerias para el modelo de la red en Keras\nfrom keras.utils.vis_utils import plot_model #impresion en imagen del modelo\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D,MaxPooling2D, BatchNormalization\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.layers.normalization import BatchNormalization\n\nnp.random.seed(2) #inicializacion de la semilla\nsns.set(style='white', context='notebook', palette='deep')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Conociendo el dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Cargar la data en dataframe train y test\ntrain = pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv(\"../input/test.csv\")\nprint(train.shape) #dimensiones del train\nprint(test.shape) #dimensiones del test\ntrain.head() ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train[\"label\"] #el dataset train incluye el label de que numero es del 0 al 9","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Voy a guardar el label en la variable Y_train\nY_train = train[\"label\"]\n\n# y se la borro a train y lo guardo X_train\nX_train = train.drop(labels = [\"label\"],axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#seaborn.countplot Muestra los conteos de observaciones en cada  categoria usando barras.\ngrafica = sns.countplot(Y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Normalizacion y Reshape"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train / 255.0\ntest = test / 255.0\n\nX_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Label encoding"},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"random_seed=2\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = plt.imshow(X_train[0][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Arquitectura final\n\n\nmodel = Sequential()\n\n#Conv2D->relu ->Conv2D->relu ->MaxPool2D -> Dropout\nmodel.add(Conv2D(filters = 32, strides = (1, 1), kernel_size = (7,7),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(filters = 64, strides = (1, 1), kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.3))\n\n#Conv2D->relu ->Conv2D->relu ->MaxPool2D -> Dropout\nmodel.add(Conv2D(filters = 128, strides = (1, 1), kernel_size = (4,4),padding = 'Same', \n                 activation ='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(filters = 256, strides = (2, 2), kernel_size = (2,2),padding = 'Same', \n                 activation ='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.3))\n\n#-> Flatten -> Dense -> Dropout-> Dense -> Dropout -> Prediccion\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(126, activation = \"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\nmodel.add(Dense(10, activation = \"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()\nmodel.compile(optimizer = 'adam' , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(\n        rotation_range=15,  #girar aleatoriamente las imágenes en el rango (grados, 0 a 180)\n        zoom_range = 0.15, # Ampliar imagen\n        width_shift_range=0.1,  # cambiar aleatoriamente las imágenes horizontalmente \n        height_shift_range=0.1) # cambiar aleatoriamente las imágenes verticalmente \n        #otra prueba que hicimos\n    #rotation_range=8, width_shift_range=0.08, shear_range=0.3, height_shift_range=0.08, zoom_range=0.08)\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n#Impresion de la configuracion en el dataGenerator de forma random se escogen las observaciones pero se muestran siempre 9\nfor x_batch, y_batch in datagen.flow(X_train, Y_train, batch_size=9): #se le pasa la configuracion anterior del datagen\n   \n    for i in range(0, 9):\n        pyplot.subplot(330 + 1 + i)\n        pyplot.imshow(x_batch[i].reshape(28, 28), cmap=pyplot.get_cmap('gray'))\n    pyplot.show()\n    break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size=32\nepochs=36\n\n\nhistory = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size), validation_data = (X_val,Y_val),\n                              steps_per_epoch=X_train.shape[0] // batch_size, epochs = epochs\n                              , callbacks=[learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Graficas de loss y accuracy"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(2,1)\nax[0].plot(history.history['loss'], color='b', label=\"Entrenamiento loss\")\nax[0].plot(history.history['val_loss'], color='r', label=\"Validacion loss\",axes =ax[0])\nlegend = ax[0].legend(loc='best', shadow=True)\n\nax[1].plot(history.history['acc'], color='b', label=\"Entrenamiento accuracy\")\nax[1].plot(history.history['val_acc'], color='r',label=\"Validacion accuracy\")\nlegend = ax[1].legend(loc='best', shadow=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"_, train_acc = model.evaluate(X_train, Y_train, verbose=0)\n_, test_acc = model.evaluate(X_val, Y_val, verbose=0)\nprint('Train: %.3f, Test: %.3f' % (train_acc, test_acc))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Imprimir la matriz mas grande\nplt.figure(1)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model Complexity Graph:  Training vs. Validation Loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validate'], loc='upper right')\n\nplt.figure(2)\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('Model Accuracy Graph:  Training vs. Validation accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validate'], loc='upper right')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Matriz de Confusión"},{"metadata":{"trusted":true},"cell_type":"code","source":"#funcion que imprime la matriz de confusion\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n  \n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('Valor Verdadero')\n    plt.xlabel('Valor Predicho')\n\n# Predecir los valores del set de validación\nY_pred = model.predict(X_val)\n#Convertir la prediccion a vectores one hot (categoricas)\nY_pred_classes = np.argmax(Y_pred,axis = 1) \n#Convertir las observaciones a vectores one hot (categoricas)\nY_true = np.argmax(Y_val,axis = 1) \n#desplegar matriz\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# graficar matriz\nplot_confusion_matrix(confusion_mtx, classes = range(10)) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prediccion de Resultados"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"result = model.predict(test)\nresult = np.argmax(result, 1)\npredictions = result.T\nresult = pd.DataFrame({'ImageId': range(1,len(predictions)+1), 'Label': predictions})\nresult.to_csv('result.csv', index=False, encoding='utf-8')","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}