{"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_minor":4,"nbformat":4,"cells":[{"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntrain","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ntest","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Now we have train and test\n# to do list, Part 1:\n# 1- create X, y from train and test\n# 2- show some samples\n# 3- Normalize Xs\n# 4- reshape Xs to (-1,28,28,1)\n# 5- LabelEncoding of ys using to_categorical","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train.shape, test.shape)  # we don't have y_test","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = train.drop('label',axis=1)\ny_train = train['label']","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nsamp1 = np.array(X_train.iloc[0]).reshape(28,28)\nplt.imshow(samp1, cmap='gray')\nplt.axis('off')\nplt.title('Sample 0')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"samp5 = np.array(X_train.iloc[4]).reshape(28,28)\nplt.imshow(samp5, cmap='gray')\nplt.title('sample 5')\nplt.axis('off')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# normalize\nfrom sklearn.preprocessing import StandardScaler\n\nSS = StandardScaler()\nX_train = SS.fit_transform(X_train)\ntest = SS.fit_transform(test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# because Xs are DataFrame for reshape we use .values method\n# X_train = X_train.values.reshape(-1,28,28,1)\n# test = test.values.reshape(-1,28,28,1)\n\nX_train = X_train.reshape(-1,28,28,1)\ntest = test.reshape(-1,28,28,1)\n\nprint(\"x_train shape: \",X_train.shape)\nprint(\"test shape: \",test.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# label encoding\nfrom keras.utils.np_utils import to_categorical\n\ny_train = to_categorical(y_train , num_classes=10)\ny_train.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# we don't have y_test so it's better to use validation\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size = 0.1, random_state=2)\nprint(\"x_train shape\",X_train.shape)\nprint(\"x_test shape\",X_val.shape)\nprint(\"y_train shape\",y_train.shape)\nprint(\"y_test shape\",y_val.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# CNN Model\nimport tensorflow as tf\n\ncnn = tf.keras.Sequential()\ncnn.add(tf.keras.layers.Conv2D(filters=3, kernel_size=(5,5), input_shape=(28,28,1)))\ncnn.add(tf.keras.layers.Conv2D(filters=3, kernel_size=(5,5)))\ncnn.add(tf.keras.layers.MaxPool2D(pool_size=(2,2)))\ncnn.add(tf.keras.layers.Conv2D(filters=3, kernel_size=(5,5)))\ncnn.add(tf.keras.layers.MaxPool2D(pool_size=(2,2)))\ncnn.add(tf.keras.layers.Flatten())\ncnn.add(tf.keras.layers.Dense(10, activation='softmax'))\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.optimizers import Adam\nopt = Adam()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.compile(optimizer=opt , loss = \"categorical_crossentropy\", metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist = cnn.fit(X_train, y_train, batch_size=256, epochs=10,validation_data=(X_val,y_val),verbose=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = cnn.predict(test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.evaluate(X_val, y_val)[1]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(hist.history['val_accuracy'])\nplt.xlabel(\"Number of Epochs\")\nplt.ylabel(\"accuracy of validation\")\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}