{"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":"# Imports\n\nimport csv\nimport zipfile\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Read the labels and the pixel data in each row (pixels of each image) into two lists respectively\n\nimport csv\n\n# image_pixels is a list of lists. Each list will have the pixel data from each row in the CSV\nimage_pixels = []\nlabels = []\nwith open('/kaggle/input/digit-recognizer/train.csv', 'r') as csvfile:\n    reader = csv.reader(csvfile, delimiter=',')\n    next(reader)\n    for row in reader:\n      labels.append(int(row[0]))\n      image_pixels_tmp = []\n      for i in range(1,785):\n        image_pixels_tmp.append(int(row[i]))\n      image_pixels.append(image_pixels_tmp)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Repeat process for test data\n\nimage_pixels_test = []\npixels_list_fin_test = []\nwith open(\"/kaggle/input/digit-recognizer/test.csv\", 'r') as csvfile:\n    reader = csv.reader(csvfile, delimiter=',')\n    next(reader)\n    for row in reader:\n      image_pixels_test_tmp = []\n      for i in range(0,784):\n        image_pixels_test_tmp.append(int(row[i]))\n      image_pixels_test.append(image_pixels_test_tmp)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Total number of training images\n\nlen(image_pixels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Identify unique labels in the dataset\n\nprint(set(labels))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert list into numpy array\n\nimage_pixels = np.array(image_pixels)\nimage_pixels_test1 =  np.array(image_pixels_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert labels into numpy array\n\nlabels_final = np.array(labels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reshape array into a rank of 3 as follows for plotting\n\nimage_pixels_train1 = image_pixels.reshape(42000,28,28)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(image_pixels_train1[3])\nplt.colorbar()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# reshape and change data type array for processing by neural network model\n\nimage_pixels_train_final = image_pixels.reshape(42000,28,28,1).astype(float)\nimage_pixels_test_final = image_pixels_test1.reshape(28000,28,28,1).astype(float)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Normalize pixel values\n\nimage_pixels_train_final *= 1./255.\nimage_pixels_test_final *= 1./255.","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define model\n\nmodel = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(32, (5,5), activation='relu',input_shape=(28,28,1)),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(128, activation='relu'),\n    tf.keras.layers.Dense(64, activation='relu'),\n    tf.keras.layers.Dense(10, activation='softmax')\n])\n\nmodel.compile(loss='sparse_categorical_crossentropy',\n              optimizer=Adam(),\n              metrics=['accuracy'])\n\nmodel.fit(image_pixels_train_final, labels_final, epochs=10, batch_size=32)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# To save the model\n\nmodel.save(\"digit_mymodel.h5\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Retrieve the model\nfrom tensorflow import keras\n\nmodel = keras.models.load_model('digit_mymodel.h5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model prediction using test dataset\n\npred_test = np.argmax(model.predict(image_pixels_test_final), axis=-1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_test.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import results into pandas dataframe\n\nimport pandas as pd\npredictions = pd.DataFrame(np.argmax(model.predict(image_pixels_test_final), axis=-1),index=np.arange(1,28001),columns=['result'])\npredictions.insert(0,'Id',predictions.index)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Thank you","metadata":{},"execution_count":null,"outputs":[]}]}