{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"markdown","source":"Kaggle: https://www.kaggle.com/c/digit-recognizer"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_DIR = '../input/digit-recognizer/train.csv'\nTEST_DIR = '../input/digit-recognizer/test.csv'","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Explantory Data Analyisis"},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_example(X, y, row):\n    print(y[row])\n    plt.imshow(X[row].reshape((28, 28)))\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_examples(X, y, show_how_many=4):\n    classes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n    for col, cls in enumerate(classes):\n        idxs = np.nonzero([i == cls for i in y]) # Note: nonzero means i==cls is true.\n        idxs = np.random.choice(idxs[0], show_how_many)\n        for i , idx in enumerate(idxs):\n            plt_idx = i * len(classes) + col + 1\n            plt.subplot(show_how_many, len(classes), plt_idx)\n            plt.imshow(X[idx].reshape((28, 28)))\n            plt.axis(\"off\")\n            if i == 0:\n                plt.title(cls)      \n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"1.Take a Glance at the Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(TRAIN_DIR, sep=',', header=0)\ntest = pd.read_csv(TEST_DIR, sep=',', header=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"2. Show Some Examples"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_example(train.values[:300, 1:], train.values[:300, 0], 100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_examples(train.values[:300, 1:], train.values[:300, 0])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prepare Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(TRAIN_DIR, sep=',', header=0)\ntest = pd.read_csv(TEST_DIR, sep=',', header=0)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Training Set, Cross Validation Set, Test Set"},{"metadata":{"trusted":true},"cell_type":"code","source":"X = train.drop('label', axis = 1).values.reshape(-1, 28, 28, 1)\ny = to_categorical(train['label'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X / 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=0, test_size=0.2)\nprint(f'Training Set - X train shape: {X_train.shape}, y train shape: {y_train.shape}')\nprint(f'Validation Set - X val shape: {X_val.shape}, y train shape: {y_val.shape}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test = test.values.reshape(-1, 28, 28, 1)\nX_test = X_test / 255\nprint(f'Test Set - X test shape: {X_test.shape}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense,Conv2D,Flatten,MaxPool2D,Dropout,BatchNormalization\nfrom keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cnn = Sequential()\n\ncnn.add(Conv2D(filters = 32, \n               kernel_size = (3, 3), \n               padding = 'Same',\n               activation = 'relu', \n               input_shape = (28, 28, 1)))\ncnn.add(MaxPool2D(2, 2))\ncnn.add(Dropout(0.2))\n\ncnn.add(Conv2D(filters = 64, \n               kernel_size = (3, 3), \n               padding = 'Same',\n               activation = 'relu'))\ncnn.add(MaxPool2D(2, 2))\ncnn.add(Dropout(0.2))\n\ncnn.add(Conv2D(filters = 128, \n               kernel_size = (3, 3), \n               padding = 'Same',\n               activation = 'relu'))\ncnn.add(MaxPool2D(2, 2))\ncnn.add(Dropout(0.2))\n\ncnn.add(Flatten())\ncnn.add(Dense(64, activation='relu'))\ncnn.add(Dropout(0.4))\ncnn.add(Dense(10, activation='softmax'))\n\ncnn.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer=Adam(learning_rate=0.001,beta_1=0.9,beta_2=0.999)\ncnn.compile(optimizer=optimizer,loss=['categorical_crossentropy'],metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train"},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCH = 10\nBATCH_SIZE = 64","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# history = cnn.fit(X_train, y_train, batch_size=BATCH_SIZE, \n#                   epochs=EPOCH, verbose=2, \n#                   validation_data=(X_val, y_val))\nhistory = cnn.fit(X, y, batch_size=BATCH_SIZE, epochs=EPOCH, verbose=2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predict"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test = cnn.predict(X_test)\ny_test = np.argmax(y_test, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_example(X_test, y_test, 6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame({\"ImageId\": list(range(1,len(y_test)+1)),\\\n              \"Label\": y_test}).to_csv('submission.csv', index=False,header=True)","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}