{"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\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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#Importing Stuff\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Reading the data\ntrain=pd.read_csv('../input/digit-recognizer/train.csv')\ntest=pd.read_csv('../input/digit-recognizer/test.csv')\ny=train['label']\ntrain.drop('label',axis=1,inplace=True)\ntraining_images=train.to_numpy()\ntest_images=test.to_numpy()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Rescaling our image sizes and turning target column into a vector\ntraining_images = training_images/255.0\ntest_images = test_images/255.0\ntraining_images = training_images.reshape(42000, 28, 28, 1)\ntest_images = test_images.reshape(28000, 28, 28, 1)\ny=y.to_numpy()\ny= OneHotEncoder(sparse=False).fit_transform(y.reshape(-1,1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Creating a model using the sequential api\nmodel = tf.keras.Sequential([\n    tf.keras.layers.Conv2D(32, (5, 5),padding='same', activation='relu', input_shape=(28, 28, 1)),\n    tf.keras.layers.Conv2D(32, (5, 5),padding='same', activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    \n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Dropout(0.3),\n    \n    \n    tf.keras.layers.Conv2D(64, (3, 3),padding='same', activation='relu'),\n    tf.keras.layers.Conv2D(64, (3, 3),padding='same', activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    \n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Dropout(0.3),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(256, activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Dropout(0.5),\n    \n    tf.keras.layers.Dense(10, activation='softmax')\n    ])\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary() #Summarising out model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',patience=3,verbose=1,factor=0.5,min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Compiling and training our model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\ntrain_datagen = ImageDataGenerator(rotation_range=10,\n      width_shift_range=0.1,\n      height_shift_range=0.1,\n      zoom_range=0.1,\n      fill_mode='nearest')\n\ntrain_generator=train_datagen.flow(training_images,y,batch_size=100)\n\nmodel.fit_generator(train_generator,epochs = 40,callbacks = [learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('model1') #Saving the model incase we need it later","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"reload_model = keras.models.load_model(\"model1\") #Reloading the model we saved just now","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result=reload_model.predict(test_images) #Predciting the results\nresult = np.argmax(result,axis = 1)  #Converting the result vector to label array","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(test_images[32].reshape(28,28)) #View an image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result[32] # See how the model predicted the above image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res=pd.read_csv('../input/digit-recognizer/sample_submission.csv',index_col=None) \nres['Label']=result\nres.to_csv('Submission.csv',index=False)","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}