{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense\n\n# Input data files are available in the \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_data=pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_images=pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ntrain_images=train_data.iloc[:,1:]\ntrain_labels=train_data.iloc[:,0]\ntrain_images=train_images.to_numpy()\ntrain_labels=train_labels.to_numpy()\ntest_images=test_images.to_numpy()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#reshape data\ntrain_images=train_images.reshape(train_images.shape[0],28,28,1)\ntrain_labels=train_labels.reshape(train_labels.shape[0],1)\ntest_images=test_images.reshape(test_images.shape[0],28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def preprocess_images(imgs): # should work for both a single image and multiple images\n    sample_img = imgs if len(imgs.shape) == 2 else imgs[0]\n    assert sample_img.shape in [(28, 28, 1), (28, 28)], sample_img.shape # make sure images are 28x28 and single-channel (grayscale)\n    return imgs / 255.0\n\ntrain_images = preprocess_images(train_images)\ntest_images = preprocess_images(test_images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(10,2))\nfor i in range(5):\n    plt.subplot(1,5,i+1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    plt.imshow(train_images[i].reshape(28, 28), cmap=plt.cm.binary)\n    plt.xlabel(train_labels[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = keras.Sequential()\n# 32 convolution filters used each of size 3x3\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))\n# 64 convolution filters used each of size 3x3\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\n# choose the best features via pooling\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# randomly turn neurons on and off to improve convergence\nmodel.add(Dropout(0.25))\n# flatten since too many dimensions, we only want a classification output\nmodel.add(Flatten())\n# fully connected to get all relevant data\nmodel.add(Dense(128, activation='relu'))\n# one more dropout\nmodel.add(Dropout(0.5))\n# output a softmax to squash the matrix into output probabilities\nmodel.add(Dense(10, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam',\n              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train_images, train_labels, epochs=5,validation_split=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"probability_model = tf.keras.Sequential([model, \n                                         ])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = probability_model.predict(test_images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def submission_file(submission):\n    submission=np.argmax(predictions,axis=1)\n    submission=pd.DataFrame(submission)\n    submission.index = np.arange(1, len(submission)+1)\n    submission= submission.rename_axis('ImageId').reset_index()\n    submission=submission.rename(columns={0:'Label'})\n    submission.index = np.arange(1, len(submission)+1)\n    return submission\nsubmission=submission_file(predictions)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}