{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Hello Guys\nI'll simply put my code. For explanation, there are quite a lot of kernels you can refer to. Thanks a lot.","execution_count":null},{"metadata":{"id":"wYtuKeK0dImp","trusted":true},"cell_type":"code","source":"import csv\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom os import getcwd","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\ndf_train = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ndf_test = pd.read_csv(\"../input/digit-recognizer/test.csv\")\ndf_train.head()","execution_count":null,"outputs":[]},{"metadata":{"id":"4kxw-_rmcnVu","trusted":true},"cell_type":"code","source":"train_labels = df_train['label']\ndel df_train['label']\ndf_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_set = df_train.values\ntrain_set = train_set.reshape(42000,28,28)\ntest_set = df_test.values\ntest_set = test_set.reshape(28000,28,28)\nprint(train_set.shape, test_set.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nrandom_seed = 7\ntraining_set, validation_set, training_labels, validation_labels = train_test_split(train_set, train_labels, test_size = 0.10, random_state=random_seed)\nprint(len(validation_labels))","execution_count":null,"outputs":[]},{"metadata":{"id":"awoqRpyZdQkD","trusted":true},"cell_type":"code","source":"training_images = np.expand_dims(training_set, axis=-1)\ntesting_images = np.expand_dims(test_set, axis=-1)\nvalidation_images = np.expand_dims(validation_set, axis=-1)\n\n\n# Create an ImageDataGenerator and do Image Augmentation\ntrain_datagen = ImageDataGenerator(rescale=1.0/255,\n                                   rotation_range=10,\n                                   width_shift_range=0.1,\n                                   height_shift_range=0.1,\n                                   zoom_range=0.1)\n\nvalidation_datagen = ImageDataGenerator(rescale=1.0/255)\n    \nprint(training_images.shape)\nprint(testing_images.shape)\nprint(validation_images.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define the model\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\nankitz = ReduceLROnPlateau(monitor='val_accuracy', patience = 3, verbose=1,factor=0.5, min_lr=0.00001)\n\nmodel = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(32, (5, 5), activation='relu', input_shape=(28, 28, 1),padding='same'),\n    tf.keras.layers.Conv2D(32, (5, 5), activation='relu', padding='same'),\n    tf.keras.layers.MaxPool2D(pool_size=(2, 2),strides=(2,2)),\n    tf.keras.layers.Dropout(0.2),\n    tf.keras.layers.Conv2D(64, (5, 5), activation='relu', padding='same'),\n    tf.keras.layers.Conv2D(64, (5, 5), activation='relu', padding='same'),\n    tf.keras.layers.MaxPool2D(pool_size=(2, 2),strides=(2,2)),\n    tf.keras.layers.Dropout(0.2),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(256, activation=tf.nn.relu),\n    tf.keras.layers.Dropout(0.2),\n    tf.keras.layers.Dense(10, activation='softmax')])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"id":"Rmb7S32cgRqS","trusted":true},"cell_type":"code","source":"# Compile Model. \nmodel.compile(optimizer=tf.optimizers.Adam(),\n             loss='sparse_categorical_crossentropy',\n             metrics=['accuracy'])\n\n# Train the Model\nhistory = model.fit_generator(train_datagen.flow(training_images, training_labels, batch_size=86),\n                              epochs = 25,\n                              steps_per_epoch=training_images.shape[0] // 86,\n                              validation_data=validation_datagen.flow(validation_images, validation_labels),\n                             callbacks = [ankitz])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict_classes(testing_images)\npredictions = pd.Series(predictions, name='Label')\npredictions[:4]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),predictions],axis = 1)\n\nsubmission.to_csv(\"my_results_final.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"id":"_Q3Zpr46dsij","trusted":true},"cell_type":"code","source":"# Plot the chart for accuracy and loss on both training and validation\n%matplotlib inline\nimport matplotlib.pyplot as plt\nacc = history.history['accuracy']\nloss = history.history['loss']\nval_acc = history.history['val_accuracy']\nval_loss = history.history['val_loss']\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training accuracy and Validation Accuracy')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, loss, 'r', label='Training Loss')\nplt.plot(epochs, val_loss, 'b', label='Training Loss')\nplt.title('Training loss and Validation loss')\nplt.legend()\n\nplt.show()","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}