{"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data=pd.read_csv('../input/digit-recognizer/test.csv')\ntrain_data=pd.read_csv('../input/digit-recognizer/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"training=np.array(train_data,dtype='float32')\ntesting=np.array(test_data,dtype='float32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(training[11,1:].reshape(28,28))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(testing[11,0:].reshape(28,28))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"W_grid=15\nL_grid=15\n\nfig,axes=plt.subplots(L_grid,W_grid,figsize=(17,17))\n\naxes=axes.ravel()\n\nn_training=len(training)\n\nfor i in np.arange(0,W_grid*L_grid):\n    #Select the random no\n    index=np.random.randint(0,n_training)\n    axes[i].imshow(training[index,1:].reshape(28,28))\n    axes[i].set_title(training[index,0],fontsize=8)\n    axes[i].axis('off')\nplt.subplots_adjust(hspace=0.4)   ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Training Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train=training[:,1:]/255\ny_train=training[:,0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test=testing[:,0:]/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_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},"cell_type":"code","source":"X_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\ny_train_cat=to_categorical(y_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Model Building**"},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nfrom keras.models import Sequential\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.models import Model\nfrom keras import datasets, layers, models\nfrom keras.layers import Dense,Conv2D,MaxPooling2D,Flatten,Dropout\nmodel =Sequential()\nmodel.add(Conv2D(64,kernel_size=(3, 3),activation='relu',input_shape=(28, 28, 1)))  # Convolution Layer -1 \nmodel.add(Conv2D(64,kernel_size=(3, 3),activation='relu'))                          # Convolution Layer -2 \nmodel.add(MaxPooling2D(pool_size=(2, 2)))                                               # Pooling Layer -1\nmodel.add(BatchNormalization())                                                      # Normalization \nmodel.add(Dropout(0.25))                                                             # Set 25% to 0 to prevent overfitting \n\nmodel.add(Conv2D(filters = 128, kernel_size = (3,3),activation ='relu'))             # Convolution Layer -3 \nmodel.add(Conv2D(filters = 128, kernel_size = (3,3),activation ='relu'))             # Convolution Layer -4 \nmodel.add(MaxPooling2D(pool_size=(2,2)))                                                # Pooling Layer -2 \nmodel.add(BatchNormalization())                                                      # Normalization\nmodel.add(Conv2D(filters = 256, kernel_size = (3,3),activation ='relu'))             # Convolution Layer -5 \nmodel.add(MaxPooling2D(pool_size=(2,2)))                                                # Pooling Layer -3 \nmodel.add(Dropout(0.25))                                                             # Set 25% to 0 to prevent overfitting\n\nmodel.add(Flatten())                                                                 # Flattens input\nmodel.add(BatchNormalization())                                                      # Normalization\nmodel.add(Dense(512, activation = \"relu\"))                                           # Connection Layer -1 \nmodel.add(Dropout(0.5))                                                              #  Set 50% to 0 to prevent overfitting\nmodel.add(Dense(10, activation = \"softmax\"))     ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss=keras.losses.categorical_crossentropy,\n              optimizer=keras.optimizers.RMSprop(),\n              metrics=['accuracy'])\n\n# Define Callback function for reducting learning rate when no more improvement of accuracy\nlearning_rate_reduction = ReduceLROnPlateau(monitor='accuracy', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.3, \n                                            min_lr=0.0001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fit train&test data\nepochs_range = 60\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n#history = model.fit(X_train_tensor,y_train,batch_size=256,epochs=epochs_range,validation_data=(X_test_tensor,y_test_cat),callbacks=learning_rate_reduction )\nmodel.fit(X_train,y_train_cat,batch_size=256,epochs=epochs_range)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred=model.predict_classes(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig,axes=plt.subplots(8,8,figsize=(15,15))\n\naxes=axes.ravel()\n\nfor i in range(0,8*8):\n    axes[i].imshow(X_test[i,0:].reshape(28,28))\n    axes[i].set_title(\"Prediction Class = {:0.1f}\".format(y_pred[i]))\n    axes[i].axis('off')\nplt.tight_layout()\nplt.subplots_adjust(wspace=0.5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample=pd.read_csv('../input/digit-recognizer/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"temp=pd.DataFrame({'ImageId':sample['ImageId'],'Label':y_pred})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"temp.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"csv_data=temp.to_csv('pred.csv',index=False)","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}