{"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":"from sklearn.model_selection import train_test_split\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom keras.utils.np_utils import to_categorical\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"","_uuid":"","trusted":true},"cell_type":"code","source":"import pandas as pd\nsample_submission = pd.read_csv(\"../input/digit-recognizer/sample_submission.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")\ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X=train.drop(labels=[\"label\"],axis=1)\ny=train[\"label\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Normalizing the data**"},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X / 255.0\ntest = test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","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.1, random_state=2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Examine image dimensions**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# printing the number of samples in X_train, X_test, y_train, y_test\nprint(\"Initial shape of dimensions of X_train\", str(X_train.shape))\n\nprint(\"Number of samples in our training data: \"+ str(len(X_train)))\nprint(\"Number of labels in out training data: \"+ str(len(y_train)))\nprint(\"Number of samples in our test data: \"+ str(len(X_test)))\nprint(\"Number of labels in out test data: \"+ str(len(y_test)))\nprint()\nprint(\"Dimensions of x_train:\" + str(X_train[0].shape))\nprint(\"Labels in x_train:\" + str(y_train.shape))\nprint()\nprint(\"Dimensions of X_test:\" + str(X_test[0].shape))\nprint(\"Labels in X_test:\" + str(y_test.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = plt.imshow(X_train[1][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**making the model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes = y_test.shape[1]\nnum_pixels = X_train.shape[1] * X_train.shape[2]\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\nfrom keras.optimizers import SGD\n\n#applying adam optimizer to reduce losses\noptimizer=keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)\ndropout=0.2\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3,3),activation='relu',input_shape=(28,28,1)))#adding convolutional layer\nmodel.add(Conv2D(64, (3,3),activation='relu',input_shape=(28,28,1)))#adding convolutional layer        \n\nmodel.add(MaxPooling2D(pool_size=(2, 2)))#adding pooling layer\nmodel.add(Dropout(dropout))#regularizing using dropout with 20%\nmodel.add(Flatten()) #flattening the input to apply Dense()\nmodel.add(Dense(128, activation='relu'))#making a network with output of 128 dimensionality\n\nmodel.add(Dropout(dropout))#regularizing using dropout with 20%\nmodel.add(Dense(num_classes, activation='softmax'))#making a network with output of y_test.shape[1] dimensionality\nmodel.compile(loss = 'categorical_crossentropy',optimizer = optimizer,metrics = ['accuracy'])\n\nprint(model.summary())\n                 \n                 \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#training the model\nbatch_size = 66\nepochs = 10\n\nhistory = model.fit(X_train,y_train,batch_size = batch_size,epochs = epochs,verbose = 1,validation_data = (X_test, y_test))\n                                                        \nscore = model.evaluate(X_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib inline\nimport matplotlib.pyplot as plt\n\nhistory_dict = history.history\n\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\nepochs = range(1, len(loss_values) + 1)\n\nline1 = plt.plot(epochs, val_loss_values, label='Validation/Test Loss')\nline2 = plt.plot(epochs, loss_values, label='Training Loss')\nplt.setp(line1, linewidth=2.0, marker = '+', markersize=10.0)\nplt.setp(line2, linewidth=2.0, marker = '4', markersize=10.0)\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.grid(True)\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib inline\nimport matplotlib.pyplot as plt\n\nhistory_dict = history.history\n\nacc_values = history_dict['accuracy']\nval_acc_values = history_dict['val_accuracy']\nepochs = range(1, len(loss_values) + 1)\n\nline1 = plt.plot(epochs, val_acc_values, label='Validation/Test Accuracy')\nline2 = plt.plot(epochs, acc_values, label='Training Accuracy')\nplt.setp(line1, linewidth=2.0, marker = '+', markersize=10.0)\nplt.setp(line2, linewidth=2.0, marker = '4', markersize=10.0)\nplt.xlabel('Epochs') \nplt.ylabel('Accuracy')\nplt.grid(True)\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#saving the model\nmodel.save(\"/mnist_simple_cnn_10_epochs.h5\")\nprint(\"Model save\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#loading model\nfrom keras.models import load_model\nclassifier = load_model(\"/mnist_simple_cnn_10_epochs.h5\")\nprint(\"Model loaded\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.predict(test)\n\n\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"submission.csv\",index=False)","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":1}