{"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":{"_uuid":"ff4425d2ccae0f5db9ed9fa609655f7531f06c78"},"cell_type":"markdown","source":"# Loading the Data\n### Frist load the data using pandas Lib in two train and test sets.\n"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# Loading Data\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n%matplotlib inline\n\ntrain = pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv(\"../input/test.csv\")\n\ny_train = train[\"label\"]\nx_train = train.drop(labels = [\"label\"], axis=1)\n\ndel train\n\n#g = sns.countplot(y_train)\n#y_train.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"035dab0f66c0767f5b7e76b3954bdf3de6774327"},"cell_type":"markdown","source":"# Normalization\n### to change the grayscale range from [0..255] to [0..1]"},{"metadata":{"trusted":true,"_uuid":"b33bb87da64bff80abf5b597a336caaf13cb10ec"},"cell_type":"code","source":"# Normalizing Data\nx_train = x_train / 255.0\ntest = test / 255.0\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a4d0b919ef5ea2572faf6fe4ddbbbe59484cd417"},"cell_type":"markdown","source":"# Reshape\n### The images are in vector form with 784 elements, now we reshapeinto 28x28x1 matrices."},{"metadata":{"trusted":true,"_uuid":"50589d88535109450ffd4226e4e5f43cca56bef4"},"cell_type":"code","source":"#Reshaping images in 3 dimensions\nx_train = x_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1df0d64a8ff171f3729299202cbaa06ff7953c8a"},"cell_type":"markdown","source":"# Label encoding\n### We have 10 labels, 0,1,...,9. They should be encode in one hot vector, for exp : 7-->> [0,0,0,0,0,0,0,1,0,0]"},{"metadata":{"trusted":true,"_uuid":"53d106a54ed7aaaebde7d244ce783aa3190f56e3"},"cell_type":"code","source":"# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])\nfrom keras.utils.np_utils import to_categorical\n\ny_train = to_categorical(y_train, num_classes = 10)\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5ce9ddf0c9a6b674491a001bdd912375dcedc66a"},"cell_type":"markdown","source":"# Spliting data\n### in order to have a better training and more training accuracy, spliting data to train and validation set is good idea. "},{"metadata":{"trusted":true,"_uuid":"a296fe101e6e09a7e56c631b18b4be0b6b114dcb"},"cell_type":"code","source":"#Spliting data into train and validation set\nfrom sklearn.model_selection import train_test_split\n\nrandom_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)\n#g = plt.imshow(x_train[5][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"67106fd7733c56506e8fd278a75821ab6f107fcc"},"cell_type":"markdown","source":"# Train and define CNN model\n### CNN layers and kernels and those activation functions and other stuffs could be a very long story, I think, easy google \"CNN model in keras\" or some thing else :) "},{"metadata":{"trusted":true,"_uuid":"07df59af2bff54d30fcb97bf351e1fadf9ad61e2"},"cell_type":"code","source":"#CNN Model\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.layers.normalization import BatchNormalization\n\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32,kernel_size=3,activation='relu',input_shape=(28,28,1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32,kernel_size=3,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32,kernel_size=5,strides=2,padding='same',activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(64,kernel_size=3,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64,kernel_size=3,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64,kernel_size=5,strides=2,padding='same',activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bf2f2915f79ca658b8c28f247ef08d7d42def3f2"},"cell_type":"code","source":"epochs = 60 # but actually it should be more than 1\nbatch_size = 86\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9af6e2f8e5779fb99de50a25015323ec9ad2b0c5"},"cell_type":"markdown","source":"# Data augmentation\n### With these method we make more training images from our train data set using some image preprocessing techniks."},{"metadata":{"trusted":true,"_uuid":"709a25f5675e77dbdf8e61544f5e8f68c5d728e5"},"cell_type":"code","source":"#Data augmentation\nfrom keras.preprocessing.image import ImageDataGenerator\n\ndatageneration = ImageDataGenerator(\n        featurewise_center=False,  \n        samplewise_center=False,  \n        featurewise_std_normalization=False,  \n        samplewise_std_normalization=False, \n        zca_whitening=False,  \n        rotation_range=10, \n        zoom_range = 0.1,\n        width_shift_range=0.1, \n        height_shift_range=0.1,  \n        horizontal_flip=False,  \n        vertical_flip=False)  \n\ndatageneration.fit(x_train)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"945c0bde45545ce5290a372bcbc9ffdac68ded10"},"cell_type":"code","source":"#fitting the model\nhistory = model.fit_generator(datageneration.flow(x_train,y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (x_val,y_val),\n                              verbose = 2, steps_per_epoch=x_train.shape[0] // batch_size)\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3ee1b29e54ea7756872c5a8d31d7087b6ea6b123"},"cell_type":"markdown","source":"# Confusion Matrix\n### a visual represetation of model drawbacks."},{"metadata":{"trusted":true,"_uuid":"2137fd924cfef2a9886af47a3719ed6a7b5352ce"},"cell_type":"code","source":"# Confusion matrix \nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\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('True label')\n    plt.xlabel('Predicted label')\n\n# Predict the values from the validation dataset\ny_pred = model.predict(x_val)\n# Convert predictions classes to one hot vectors \ny_pred_classes = np.argmax(y_pred,axis = 1) \n# Convert validation observations to one hot vectors\ny_true = np.argmax(y_val,axis = 1) \n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(y_true, y_pred_classes) \n# plot the confusion matrix\nplot_confusion_matrix(confusion_mtx, classes = range(10)) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ff99d9d9355a51aab8e52171607ac8226e333671"},"cell_type":"code","source":"model.save(\"dig_rec.model\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fec13258258701d0ae2e25036a9e448faba0c26a"},"cell_type":"code","source":"from keras.models import model_from_json\n\n# serialize model to JSON\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n    json_file.write(model_json)\n# serialize weights to HDF5\nmodel.save_weights(\"model.h5\")","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6cea963f5fc5c80d410eb6eb79393fcf6a771a59"},"cell_type":"markdown","source":"# Predicting the test set"},{"metadata":{"trusted":true,"_uuid":"a3596106c46ec6f20f1c659ad0697d4f5fe9c4f0"},"cell_type":"code","source":"# predict results\nresults = model.predict(test)\n\n# select the indix with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"32147d08e9302f2b0cf3a0cd24b7c23a2e0ae90a"},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist_datagen.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8aa900c2bf4a4a9d26df99d8eb027810662a7f08"},"cell_type":"markdown","source":"# **Brief but Useful ;)**"}],"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}