{"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":"# Load datasets\ntrain = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import libraries\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.datasets import mnist","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.head(2)","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":"X_train.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Now, reshape our data to image dimension\nX_train = X_train.values.reshape(42000,28,28,1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test to see a single image\nsingle_img = X_train[0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#single_img","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"single_img.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# lets see how the image looks like\nplt.imshow(single_img)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"## Preprocessing Data","metadata":{}},{"cell_type":"code","source":"y_train","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert y_train to categorical values\nexample = to_categorical(y_train)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example[0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_cat_train = to_categorical(y_train,10)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"single_img.max()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"single_img.min()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# We should normalize our training data\nX_train = X_train/255","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lets see example when it scaled\nscaled_one = X_train[3]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"scaled_one.max()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make sure it's still the image\nplt.imshow(scaled_one)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check again the shape of training data\nX_train.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training our model\n","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Dropout, Input\nfrom tensorflow.keras.optimizers import Adam","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\n\n# First add Convolutional Layer\nmodel.add(Conv2D(filters=32, kernel_size=(4,4), input_shape=(28,28,1),\n                activation='relu'))\n# Pooling layer\nmodel.add(MaxPool2D(pool_size=(2,2)))\n# Flatten layer is to flatten the images from 28 by 28 to 764 before final layer\nmodel.add(Flatten())\n# Add Dense layer\nmodel.add(Dense(128, activation='relu'))\n#model.add(Dense(64, activation='relu'))\n# Last layer is classifier\nmodel.add(Dense(10, activation='softmax'))\n\n# Compile our model\nopt = Adam(learning_rate=0.005)\nmodel.compile(loss='categorical_crossentropy',\n             optimizer=opt,\n              metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\nearly_stop = EarlyStopping(monitor='accuracy',patience=3, verbose=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(X_train, y_cat_train,epochs=100,callbacks=[early_stop],batch_size=16)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.metrics_names","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"losses = pd.DataFrame(model.history.history)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"losses.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ntest.shape\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = test.values.reshape(28000,28,28,1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict_classes(test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(predictions)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#test\nimgId = list(range(1,28001))\nimgId = pd.Series(imgId)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imgId","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.DataFrame({'ImageID':imgId , 'Label': predictions})\nsub.to_csv(\"test_submission.csv\", index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}