{"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":"df_train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ndf_test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ndf_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"train\",df_train.shape)\nprint(\"test\", df_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_y = df_train['label']\ndf_train.drop('label', 1, inplace = True)\nprint(\"train\", df_train.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X=df_train.iloc[:,:-1].values\nY=df_train['label'].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X=X/255.0\ndf_test=df_test/255.0\nX = X.reshape(-1,28,28,1)\ndf_test=df_test.values.reshape(-1,28,28,1)\nY=Y.reshape(-1,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten, Activation, Input, Convolution2D, BatchNormalization\nimport pandas as pd\nimport os\nimport numpy as np\nfrom keras.models import load_model\nimport tensorflow as tf\nimport keras.backend as K\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam, RMSprop\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.utils import to_categorical\nimport matplotlib.pyplot as plt\nimport random\nimport cv2\nimport time","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y = to_categorical(Y, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.05,random_state=90)\nx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.05, random_state=90)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class CNNmodel:\n    @staticmethod\n    def build(width, height, depth, classes):\n        # initialize the model\n        model = Sequential()\n        inputShape = (height, width, depth)\n \n        # if we are using \"channels first\", update the input shape\n        if K.image_data_format() == \"channels_first\":\n            inputShape = (depth, height, width)\n\n        # first set of CONV => RELU => POOL layers\n        model.add(Convolution2D(32, (3, 3), input_shape=inputShape,activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        model.add(Convolution2D(32, (3, 3), activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        model.add(MaxPooling2D(pool_size=(2, 2)))   # reduces to 16x16x3xnum_filters\n        model.add(Dropout(0.2))\n\n        # second set of CONV => RELU => POOL layers\n        model.add(Convolution2D(2*48, (3, 3), activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        model.add(Convolution2D(2*48, (3, 3), activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        model.add(MaxPooling2D(pool_size=(2, 2)))   # reduces to 4x4x3x(4*num_filters)\n        model.add(Dropout(0.2))\n\n        # first (and only) set of FC => RELU layers\n        model.add(Convolution2D(64, (3, 3), activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        model.add(Convolution2D(64, (3, 3), activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        model.add(MaxPooling2D(pool_size=(2, 2)))   # reduces to 4x4x3x(4*num_filters)\n        model.add(Dropout(0.2))\n \n        # softmax classifier\n        \n        model.add(Convolution2D(128, (3, 3), activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        model.add(Convolution2D(128, (3, 3), activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        model.add(MaxPooling2D(pool_size=(2, 2)))   # reduces to 4x4x3x(4*num_filters)\n        model.add(Dropout(0.2))\n\n        model.add(Convolution2D(256, (3, 3), activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        model.add(Convolution2D(256, (3, 3), activation='relu',padding='same'))\n        model.add(BatchNormalization(axis=-1))\n        # reduces to 4x4x3x(4*num_filters)\n        model.add(Dropout(0.2))\n\n        model.add(Flatten())\n        model.add(Dense(units=256,activation='relu'))\n        model.add(BatchNormalization())\n        model.add(Dropout(0.3))\n        model.add(Dense(10, activation = \"softmax\"))\n        # return the constructed network architecture\n        return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCHS = 50\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"aug = 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=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.1, # Randomly zoom image \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\n\naug.fit(x_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = CNNmodel.build(width=28, height=28, depth=1, classes=10)\nmodel.compile(optimizer = 'adam' , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])\n\n# train the network\nH = model.fit_generator(aug.flow(x_train,y_train, batch_size=32),\n                              epochs = 50, validation_data = (x_val,y_val),\n                              verbose = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_graph(H,EPOCHS,INIT_LR,BS):\n\n    plt.style.use(\"ggplot\")\n    plt.figure()\n    N = EPOCHS\n    plt.plot(np.arange(0, N), H.history[\"loss\"], label=\"train_loss\")\n    plt.plot(np.arange(0, N), H.history[\"val_loss\"], label=\"val_loss\")\n    plt.plot(np.arange(0, N), H.history[\"accuracy\"], label=\"train_acc\")\n    plt.plot(np.arange(0, N), H.history[\"val_accuracy\"], label=\"val_acc\")\n    plt.title(\"Training Loss and Accuracy on our system\")\n    plt.xlabel(\"Epoch #\")\n    plt.ylabel(\"Loss/Accuracy\")\n    plt.legend(loc=\"lower left\")\n    # plt.savefig(args[\"plot\"])\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_graph(H,EPOCHS,0.001,32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score=model.evaluate(x_test,y_test,verbose=1)               #evaluates the model\naccuracy=100*score[1]                                       \nprint('Test accuracy is %.4f%%' % accuracy) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score=model.evaluate(x_val,y_val,verbose=1)               #evaluates the model\naccuracy=100*score[1]                                       \nprint('Test accuracy is %.4f%%' % accuracy)                 #returns the accuracy of the model ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = model.predict(df_test)\npred = pd.DataFrame(pred)\npred['Label'] = pred.idxmax(axis=1)\npred.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred['index'] = list(range(1,len(pred)+1))\npred.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pred[['index','Label']]\nsubmission.head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.rename(columns={'index':'ImageId'},inplace = True)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv',index=False)\npd.read_csv('submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}