{"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","execution":{"iopub.status.busy":"2022-07-11T09:45:33.387339Z","iopub.execute_input":"2022-07-11T09:45:33.387710Z","iopub.status.idle":"2022-07-11T09:45:33.400584Z","shell.execute_reply.started":"2022-07-11T09:45:33.387682Z","shell.execute_reply":"2022-07-11T09:45:33.399435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import needed libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.layers import Input, Dense, Dropout, Flatten, MaxPool2D\nimport tensorflow as tf\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:33.478882Z","iopub.execute_input":"2022-07-11T09:45:33.479762Z","iopub.status.idle":"2022-07-11T09:45:33.490683Z","shell.execute_reply.started":"2022-07-11T09:45:33.479724Z","shell.execute_reply":"2022-07-11T09:45:33.489524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# read train and testing data\ntrain_data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ntrain_data.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:33.554663Z","iopub.execute_input":"2022-07-11T09:45:33.555424Z","iopub.status.idle":"2022-07-11T09:45:37.479073Z","shell.execute_reply.started":"2022-07-11T09:45:33.555387Z","shell.execute_reply":"2022-07-11T09:45:37.476940Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# split labels from training data\ntrain_label = train_data['label']\ntrain_data.drop('label', axis = 1, inplace = True)","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:37.481710Z","iopub.execute_input":"2022-07-11T09:45:37.482458Z","iopub.status.idle":"2022-07-11T09:45:37.600273Z","shell.execute_reply.started":"2022-07-11T09:45:37.482416Z","shell.execute_reply":"2022-07-11T09:45:37.599029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check for null values\ntrain_data.isnull().sum().sum()","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:37.607981Z","iopub.execute_input":"2022-07-11T09:45:37.611334Z","iopub.status.idle":"2022-07-11T09:45:37.678425Z","shell.execute_reply.started":"2022-07-11T09:45:37.611292Z","shell.execute_reply":"2022-07-11T09:45:37.677222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# display first 100 images\ndef plot_images(rows, columns, images, labels):\n    '''\n    Plot first 100 images\n    INPUTS:\n        rows: number of rows we want to display images on it\n        columns: number of images we want to display in each row\n        images: consist of 100 images each image consist 28*28 pixels\n        labels: truth value for each image\n    '''\n    # reshape pixels to be 28*28\n    images = np.array(train_data).reshape(-1,28,28)\n    fig, x= plt.subplots(rows, columns, constrained_layout=True,figsize=(15,8))\n    plt.setp(x, xticks=[], yticks=[])\n    for i in range (len(x)):\n        for j in range (len(x[0])):\n            index = i*columns+j\n            x[i,j].set_title(labels[index])\n            x[i,j].imshow(images[index], cmap=plt.cm.binary)\n            \nnum_columns = 10\nplot_images(num_columns, num_columns, train_data[:num_columns*num_columns], train_label[:num_columns*num_columns])","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:37.685591Z","iopub.execute_input":"2022-07-11T09:45:37.688232Z","iopub.status.idle":"2022-07-11T09:45:43.461757Z","shell.execute_reply.started":"2022-07-11T09:45:37.688195Z","shell.execute_reply":"2022-07-11T09:45:43.460775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.random.set_seed(42)\nmodel = Sequential()\nmodel.add(Conv2D(filters=32, kernel_size=3, strides=1, padding='same', activation='relu', input_shape=(28, 28, 1)))\nmodel.add(Conv2D(filters=64, kernel_size=3, strides=1, padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=2, strides=2))\nmodel.add(Conv2D(filters=256, kernel_size=2, strides=1, padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=2, strides=2))\nmodel.add(Flatten())\nmodel.add(Dense(4096, activation ='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(10, activation ='softmax'))\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:43.463703Z","iopub.execute_input":"2022-07-11T09:45:43.464141Z","iopub.status.idle":"2022-07-11T09:45:43.535019Z","shell.execute_reply.started":"2022-07-11T09:45:43.464100Z","shell.execute_reply":"2022-07-11T09:45:43.533835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:43.536975Z","iopub.execute_input":"2022-07-11T09:45:43.537403Z","iopub.status.idle":"2022-07-11T09:45:43.547394Z","shell.execute_reply.started":"2022-07-11T09:45:43.537362Z","shell.execute_reply":"2022-07-11T09:45:43.546258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy',mode='max', patience=10)\nsave_best = ModelCheckpoint(\nfilepath = 'mnist.best_model.hdf5',\nverbose=2, save_best_only=True, mode='max', monitor = 'val_accuracy'\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:43.549164Z","iopub.execute_input":"2022-07-11T09:45:43.549912Z","iopub.status.idle":"2022-07-11T09:45:43.556037Z","shell.execute_reply.started":"2022-07-11T09:45:43.549875Z","shell.execute_reply":"2022-07-11T09:45:43.554824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_label = np.array(tf.keras.utils.to_categorical(train_label, 10))","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:43.557849Z","iopub.execute_input":"2022-07-11T09:45:43.558513Z","iopub.status.idle":"2022-07-11T09:45:43.568022Z","shell.execute_reply.started":"2022-07-11T09:45:43.558477Z","shell.execute_reply":"2022-07-11T09:45:43.567061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = np.array(train_data).reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:43.569723Z","iopub.execute_input":"2022-07-11T09:45:43.570503Z","iopub.status.idle":"2022-07-11T09:45:43.674410Z","shell.execute_reply.started":"2022-07-11T09:45:43.570468Z","shell.execute_reply":"2022-07-11T09:45:43.673289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.shape","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:43.678244Z","iopub.execute_input":"2022-07-11T09:45:43.678529Z","iopub.status.idle":"2022-07-11T09:45:43.685343Z","shell.execute_reply.started":"2022-07-11T09:45:43.678504Z","shell.execute_reply":"2022-07-11T09:45:43.684087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = train_data / 255","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:43.687197Z","iopub.execute_input":"2022-07-11T09:45:43.687534Z","iopub.status.idle":"2022-07-11T09:45:43.802890Z","shell.execute_reply.started":"2022-07-11T09:45:43.687502Z","shell.execute_reply":"2022-07-11T09:45:43.801670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_data, train_label,validation_split=0.2, epochs=100, batch_size=128, verbose=2,\\\n                   callbacks=[save_best,early_stopping], shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:45:43.804350Z","iopub.execute_input":"2022-07-11T09:45:43.804772Z","iopub.status.idle":"2022-07-11T09:47:26.184878Z","shell.execute_reply.started":"2022-07-11T09:45:43.804726Z","shell.execute_reply":"2022-07-11T09:47:26.183795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:47:26.186356Z","iopub.execute_input":"2022-07-11T09:47:26.186936Z","iopub.status.idle":"2022-07-11T09:48:06.594901Z","shell.execute_reply.started":"2022-07-11T09:47:26.186881Z","shell.execute_reply":"2022-07-11T09:48:06.593835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_model = tf.keras.models.load_model('mnist.best_model.hdf5')\nbest_model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:48:06.596290Z","iopub.execute_input":"2022-07-11T09:48:06.596776Z","iopub.status.idle":"2022-07-11T09:48:08.509461Z","shell.execute_reply.started":"2022-07-11T09:48:06.596737Z","shell.execute_reply":"2022-07-11T09:48:08.508438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = np.array(test_data).reshape(-1,28,28,1)\nres = best_model.predict(test_data/255)","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:48:08.510965Z","iopub.execute_input":"2022-07-11T09:48:08.511297Z","iopub.status.idle":"2022-07-11T09:48:11.505169Z","shell.execute_reply.started":"2022-07-11T09:48:08.511263Z","shell.execute_reply":"2022-07-11T09:48:11.504049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predicted = res.argmax(axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:48:11.508617Z","iopub.execute_input":"2022-07-11T09:48:11.509342Z","iopub.status.idle":"2022-07-11T09:48:11.515782Z","shell.execute_reply.started":"2022-07-11T09:48:11.509301Z","shell.execute_reply":"2022-07-11T09:48:11.514754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create submission csv file\noutput = pd.DataFrame({'ImageId':range(1,test_data.shape[0]+1),'Label': predicted})\noutput.to_csv('my_submission.csv',index = False)\nprint(\"Your submission was successfully saved!\")","metadata":{"execution":{"iopub.status.busy":"2022-07-11T09:48:11.519926Z","iopub.execute_input":"2022-07-11T09:48:11.520252Z","iopub.status.idle":"2022-07-11T09:48:11.571300Z","shell.execute_reply.started":"2022-07-11T09:48:11.520226Z","shell.execute_reply":"2022-07-11T09:48:11.570225Z"},"trusted":true},"execution_count":null,"outputs":[]}]}