{"cells":[{"metadata":{"_uuid":"2527420677992a0a54d866e1e996f1024e3967c4"},"cell_type":"markdown","source":"# Digit Recognizer with Keras"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"# Linear algebra\nimport numpy as np \n# Data processing, CSV file I/O (e.g. pd.read_csv)\nimport pandas as pd\n\n# Keras \nfrom keras.utils.np_utils import to_categorical # For convert to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense,MaxPooling2D,Flatten,Dropout,MaxPool2D\nfrom keras.layers.convolutional import Conv2D\nfrom keras import backend\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import SGD\nfrom keras.optimizers import RMSprop\nfrom keras.losses import categorical_crossentropy\nfrom keras.callbacks import ReduceLROnPlateau\n\n# Seaborn\nfrom seaborn import countplot","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# Globals constants\ninput_neurons=784  # 28 * 28 = 784\noutput_neurons=10","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a080b5a101e18d3990c864fd396957ea7f0a607e"},"cell_type":"code","source":"# Fix random seed for reproducibility\nnp.random.seed(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5b8a70678cd1e0aad240aa87ce2287a6a5186a76"},"cell_type":"code","source":"# Load the dataset\ntrain_df = pd.read_csv('../input/train.csv')\ntest_df = pd.read_csv('../input/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true,"_uuid":"baa410ec59f2a62b0ba890dc8c0a07ba2640020d"},"cell_type":"code","source":"# Apply a reshape and load to the x and y\nxtrain_df=train_df.drop(['label'], axis=1)\nytrain_df=train_df.label\n# Load data for test, just the variables without the prediction\nxtest_df = test_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2d29d4e70e9501539e730002514c80253e1f3b79"},"cell_type":"code","source":"# Free some space\ndel train_df\ndel test_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3c256dcef9de7e476d2eef1b24796dbfb3ca81e8"},"cell_type":"code","source":"# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1)\nxtrain_df = xtrain_df.values.reshape(-1, 28, 28, 1)\nxtest_df=xtest_df.values.reshape(-1, 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a5ba5eaaad82670bd41f1e2d868b23f7a757e4b0"},"cell_type":"code","source":"ytrain_df.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fa2b4a19d82ee4a7944cbc31c91e0223655f59e6"},"cell_type":"code","source":"# Chart with the quantity of fields\n_=countplot(ytrain_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"487c606bd97e685879aba0d70a9440fc47d87dd2"},"cell_type":"code","source":"# Generate categorical labels\nytrain_df = to_categorical(ytrain_df, output_neurons)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1fa4864c4c19bd6d05f78554084f0b5c852af172"},"cell_type":"markdown","source":"## Normalization"},{"metadata":{"trusted":true,"_uuid":"b3d4eda558fd6f50f3f5c272a6798edaa39a6a67"},"cell_type":"code","source":"# Function for normalize the data\ndef normalize(df):\n    df.astype(np.float32)\n    df=df/255.0\n    return df\n    \nxtrain_df=normalize(xtrain_df)\nxtest_df=normalize(xtest_df)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"14997574fa68d50ed90ea867b4a6798f5de670b3"},"cell_type":"markdown","source":"## Create the model"},{"metadata":{"trusted":true,"_uuid":"b4671611e62173d39da3082d481576f97b1ed008"},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(output_neurons, activation = \"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"cecf13f0f856073075cccbccea348def489474b4"},"cell_type":"markdown","source":"## Compile the model"},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"_uuid":"6738cd94060de8023198a3a0152d1049390e450f"},"cell_type":"code","source":"# Set a learning rate annealer\nlearning_rate_reduction = ReduceLROnPlateau(monitor='acc',patience=3,verbose=1,factor=0.5, min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d21dee7a36d409bff0f594300a600e945ac5c718","_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"# Define the optimizer\noptimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\n# optimizer = SGD(lr=0.01) # 0.9822, model 1\n# optimizer='adam' # 0.994, model 2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cd7cb994071263f6a9d9d5981d0564584dc85cf7"},"cell_type":"code","source":"model.compile(\n    loss=categorical_crossentropy,\n    optimizer=optimizer,\n    metrics=['accuracy']\n)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"4102d42c0b7b0e8a320dbf2bba00575de5b98e3b"},"cell_type":"markdown","source":"## Data Augmentation"},{"metadata":{"trusted":true,"_uuid":"59ba46fd360f69f0b797e623132ad6efbf0b1b11"},"cell_type":"code","source":"datagen = ImageDataGenerator(\n        featurewise_center=False,  # Set input mean to 0 over the dataset\n        samplewise_center=False,  # Set each sample mean to 0\n        featurewise_std_normalization=False,  # Divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # Divide each input by its std\n        zca_whitening=False,  # Apply ZCA whitening\n        rotation_range=13,  # Randomly rotate images in the range (degrees, 0 to 180) # 10\n        zoom_range = 0.13, # Randomly zoom image # 0.1\n        width_shift_range=0.1,  # Randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1,  # Randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # Randomly flip images\n        vertical_flip=False)  # Randomly flip images\n\ndatagen.fit(xtrain_df)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"868ea74481bc308936b549680c497aa0594f7a6a"},"cell_type":"markdown","source":"## Fit the model"},{"metadata":{"trusted":true,"_uuid":"6f0d8fd49d684925cb9aa2ca16a57b35ec159fbc"},"cell_type":"code","source":"model.fit_generator(\n    datagen.flow(xtrain_df, ytrain_df, batch_size=86),\n    steps_per_epoch=len(xtrain_df) // 86,\n    epochs=50,\n    callbacks=[learning_rate_reduction]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1416e9349492e07643b8c8676e93ed2bc55fe3a5","_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"# model.fit(xtrain_df, ytrain_df, epochs=30, batch_size=86,verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"607b61ea3e6f94e3787c6cdb32386c785a2c032c"},"cell_type":"markdown","source":"## Evaluate the model"},{"metadata":{"trusted":true,"_uuid":"3c6cfd85ca0d5ff584b4584cbdd94f1196e10350"},"cell_type":"code","source":"scores = model.evaluate(xtrain_df, ytrain_df)\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f9bea8f1913bed0d00bcd53ed3536dbcd05920e5","_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"predictions = model.predict(xtest_df,verbose=0)\nresults=np.argmax(predictions,axis = 1)\nresults = pd.Series(results,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\nsubmission.to_csv(\"digit_recognizer_datagen.csv\",index=False)\n# For clear the tensorflow session\nbackend.clear_session()","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}