{"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 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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#import the necessary libraries\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.optimizers import Adam,RMSprop\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.utils import np_utils,plot_model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom IPython.display import Image\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.callbacks import ReduceLROnPlateau,ModelCheckpoint,EarlyStopping\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix,accuracy_score\nfrom keras.datasets import mnist","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_mnist = pd.read_csv('../input/digit-recognizer/train.csv')\ntest_mnist = pd.read_csv('../input/digit-recognizer/test.csv') ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = train_mnist.drop(\"label\",axis=1)\ny = train_mnist['label']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X / 255.0\ntest_mnist = test_mnist / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = pd.DataFrame(X)\ny = pd.DataFrame(y)\n\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.15,random_state=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.values.reshape(X_train.shape[0],28,28,1)\nX_test = X_test.values.reshape(X_test.shape[0],28,28,1)\ntest_mnist = test_mnist.values.reshape(test_mnist.shape[0],28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, (3, 3), input_shape=(28,28,1),padding=\"SAME\"))\nmodel.add(BatchNormalization(axis=-1))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(128,(3, 3),padding=\"SAME\"))\nmodel.add(BatchNormalization(axis=-1))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n\nmodel.add(Conv2D(192,(3, 3),padding=\"SAME\"))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n\nmodel.add(Flatten())\n\n# Fully connected layer\nmodel.add(Dense(256))\n# model.add(Dense(256))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(10))\n\nmodel.add(Activation('softmax'))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',patience=3, verbose=2,factor=0.5,min_lr=0.00001)\nbest_model = ModelCheckpoint('mnist_weights.h5', monitor='val_acc', verbose=2, save_best_only=True, mode='max')\n\nearly_stopping = EarlyStopping(monitor='val_loss', min_delta=1e-10, patience=10,restore_best_weights=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gen = ImageDataGenerator(\n    featurewise_center=False,  \n        samplewise_center=False,  \n        featurewise_std_normalization=False,  \n        samplewise_std_normalization=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\ngen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"h = model.fit_generator(\n    gen.flow(X_train, y_train, batch_size=64),\n    validation_data=(X_test, y_test),\n    steps_per_epoch=len(X_train) // 64,\n    epochs=50, verbose=1,\n    callbacks=[learning_rate_reduction,best_model,early_stopping]\n    )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = model.predict(X_test)\ny_pred = np.argmax(y_pred,axis = 1)\naccuracy_score(y_test,y_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred[:20]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame(h.history).plot()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"conf_mat = confusion_matrix(y_test,y_pred)\nf,ax = plt.subplots(figsize=(7, 7))\nsns.heatmap(conf_mat, cmap='Blues',annot=True, linewidths=.5, fmt= '.1f',ax=ax)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = model.predict(test_mnist)\npred = np.argmax(pred,axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"HV_submission = pd.DataFrame({'ImageId': range(1,len(test_mnist)+1) ,'Label':pred })","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"HV_submission.to_csv(\"hv_submission1.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":1}