{"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_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import keras\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout, Lambda, Flatten\nfrom keras.optimizers import Adam, RMSprop\nfrom sklearn.model_selection import train_test_split\nfrom keras import backend as k\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.layers import BatchNormalization, Conv2D , MaxPooling2D","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9b3bbd324e520134914e529fcba972ec2a97a871"},"cell_type":"markdown","source":"## Cargamos datos del proyecto"},{"metadata":{"trusted":true,"_uuid":"8f700be41b7bb7251097338750770171f2932c43"},"cell_type":"code","source":"datos = pd.read_csv('../input/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ba4c55e96f7553931bdb6c12b9868736755c9745"},"cell_type":"code","source":"x_train = (datos.iloc[:,1:].values).astype('float32')\ny_train = (datos.iloc[:,0].values).astype('int32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ffe86adbd00f71cca74ec4dfc710f14517c6fbe0"},"cell_type":"code","source":"#Leemos datos de test\ntest = pd.read_csv('../input/test.csv')\n#print(test.head())\nx_test = test.values.astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1a30a2e060ef6ef24695badcbbbcbf625a3eac38"},"cell_type":"markdown","source":"## 3. Modificamos, normalizamos, procesamos datos"},{"metadata":{"trusted":true,"_uuid":"2b3dc56d4c1d74ed1d64e0774d37db062caeceac"},"cell_type":"code","source":"x_train = x_train.reshape(x_train.shape[0], 28, 28)\nfor i in range(6, 9):\n    plt.subplot(330 + (i+1))\n    plt.imshow(x_train[i], cmap=plt.get_cmap('gray'))\n    plt.title(y_train[i]);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5d9a268bcb7539583ba4bb4e3432756d0834b70d"},"cell_type":"code","source":"#Redimensionamos\nx_train = x_train.reshape(x_train.shape[0], 28, 28,1)\nx_test = x_test.reshape(x_test.shape[0], 28, 28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b02ac78029abddd885a9637bb791ad63f6994634"},"cell_type":"code","source":"#Normalizacion\nx_train = x_train/255\nx_test = x_test/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"09c9ce27f80313946601ab96f62a22f074bf8332"},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\ny_train= to_categorical(y_train)\nnum_classes = y_train.shape[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9015eade593c2df500ed8b21e43eccad706de902"},"cell_type":"code","source":"#Creamos datos de entrenamiento y de validacion\nX_train, X_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.10, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1d57fc55896dd7754b25c22ec7ee3460e7e689b8"},"cell_type":"markdown","source":"## 4. Creamos modelo"},{"metadata":{"trusted":true,"_uuid":"4923a3e7c114a23d7fb3d3e5d8cb82d8eb2f20c5"},"cell_type":"code","source":"model = Sequential()\nmodel.add = (Conv2D(128, (3,3), input_shape=(28, 28, 1), padding='same', activation = 'relu'))\nmodel.add = (MaxPooling2D(2,2))\nmodel.add = (BatchNormalization())\nmodel.add = (Dropout(0.2))\n    \nmodel.add = (Conv2D(128, (3,3),strides =1, padding='valid',activation='relu'))\nmodel.add = (MaxPooling2D(2,2))\nmodel.add = (BatchNormalization())\nmodel.add = (Dropout(0.2))\n\nmodel.add = (Conv2D(128, (3,3),strides =1, padding='valid',activation='relu'))\nmodel.add = (MaxPooling2D(2,2))\nmodel.add = (BatchNormalization())\nmodel.add = (Dropout(0.2))\n    \nmodel.add = (Flatten())\n    \nmodel.add = (Dense(10, activation = 'softmax'))\n\nadam = Adam(lr=0.001, decay=1e-6)\nmodel.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ba355df9773ce8258e45feacabb34e396da8974e"},"cell_type":"code","source":"def mostrar(mostrar):\n    if mostrar==True:\n        print(\"val_acc\")\n        plt.plot(h.history['val_acc'], c = 'r')\n        plt.show()\n        print(\"val_loss\")\n        plt.plot(h.history['val_loss'], c = 'r')\n        plt.show()\n#callbacks\n#filepath = '../modelo_1/{acc:.4f}-{val_acc:.4f}-{val_loss:.4f}.keras'\n#guardar = ModelCheckpoint(filepath, monitor='val_acc', verbose=0, \n#                              save_best_only=True, save_weights_only=False, mode='max')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a36637d6e7376b48efd6d476e337930ad9320391"},"cell_type":"code","source":"#h = model.fit(X_train, y_train, batch_size=128, epochs=10,  validation_data=(X_val, y_val), callbacks=[guardar])\nh = model.fit(X_train, y_train, batch_size=128, epochs=10,  validation_data=(X_val, y_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1d9e4a22c7a1f8262e39a328d37230449fde74ea"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}