{"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 20GB 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 tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPool2D \nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\n# fix random seed for reproducibility\nnp.random.seed(7)\nimport os","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntrain_data = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_data = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nInput = train_data.drop(labels = ['label'], axis = 1).values\nprint('Input \\n', Input[:2])\nOutput = train_data['label']\nprint('Output \\n', Output[:10])\n\n#Reshaping\nX_test = test_data.values\n\nInput = Input.reshape(Input.shape[0],28,28,1)\nX_test = X_test.reshape(X_test.shape[0],28,28,1)\n\n\n\n# normalize test and train set to range 0-1\nInput,X_test  = Input / 255.0, X_test / 255.0\n\n# one hot encode target values\nOutput = to_categorical(Output, num_classes = 10) \n#Labels after applying the function\nprint('Output \\n', Output[:10])\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Reshaping Images**\n*we have a 1D vecotr with 784 pixels and we have to reshape it to (28x28x1) before passing it to the CNN.\n\nThis is because Keras wants an Extra Dimension in the end, for channels. If this had been RGB images, there would have been 3 channels, but as MNIST is gray scale it only uses 1.\n*\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"#split the train for training and testing\n\n\nXtrain, Xtest, ytrain, ytest = train_test_split(Input, Output, test_size=0.2, random_state=42)\nprint(Xtrain.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Augmentation"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator , array_to_img, img_to_array , load_img\ndatagen = ImageDataGenerator(featurewise_center=True,featurewise_std_normalization=True,\n                        rotation_range=20,\nwidth_shift_range=0.2,\nheight_shift_range=0.2,\nhorizontal_flip=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#fitting the ImageDataGenerator we defined above\ndatagen.fit(x_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def cnn_model(num_classes, epochs, batch_size, Xtrain, Xtest, ytrain, ytest):\n    # build the model \n    model = Sequential() \n    model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\n    model.add(Conv2D(64, kernel_size =(3, 3), padding = 'Same',  \n                 activation ='relu')) \n    \n    model.add(MaxPool2D(pool_size =(2, 2))) \n    #model.add(Dropout(0.5))\n    #model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = 'Same', activation ='relu')) \n    model.add(Conv2D(32, kernel_size =(3, 3), padding = 'Same',  \n                 activation ='relu')) \n    \n              \n    model.add(MaxPool2D(pool_size =(2, 2))) \n    #model.add(Dropout(0.5))\n    model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = 'Same', activation ='relu')) \n    model.add(MaxPool2D(pool_size =(2, 2))) \n    #model.add(Dropout(0.5))\n    model.add(Flatten()) \n    model.add(Dense(256, activation ='relu')) \n    model.add(Dense(num_classes, activation ='softmax')) \n    #model.add(Dropout(0.5))\n    model.add(Flatten())\n    \n    # training the model \n    model.compile(loss = keras.losses.categorical_crossentropy, \n                  optimizer = keras.optimizers.SGD(lr = 0.01), \n                  metrics =['accuracy']) \n\n    # fitting the model \n    model.fit(Xtrain, ytrain, \n              batch_size = batch_size, \n              epochs = epochs, \n              verbose = 1, \n              validation_data =(Xtest, ytest)) \n\n    # evaluating and printing results \n    score = model.evaluate(Xtest, ytest, verbose = 0) \n    #print('Test loss:', score[0]) \n    #print('Test accuracy:', score[1]) \n    \n    \n\n    y_pred = model.predict(X_test)\n\n\n    \n    return score[0], score[1], y_pred;\n\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TestLoss, TestAccuracy, y_pred = cnn_model(10, 10, 64, Xtrain, Xtest, ytrain, ytest)\n\nprint('Test loss:', TestLoss) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = [np.argmax(y_t) for y_t in y_pred]\n\nprint('Test accuracy:', TestAccuracy) \n\n\npredictions_test = []\n\nfor i in y_pred:\n    predictions_test.append(i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result =  pd.DataFrame({\n        \"ImageId\": test_data.index+1,\n        \"Label\": predictions_test\n    })\n\nresult.to_csv('submission.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}