{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Basic libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Import the backend\nimport tensorflow as tf\n\n# Data preprocessing\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.utils import to_categorical\n\n# Model architecture\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization\nfrom tensorflow.keras.callbacks import LearningRateScheduler, EarlyStopping, ReduceLROnPlateau\n\n# Model evaluation\nfrom sklearn.metrics import accuracy_score","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load the data\ntrain_dataset = pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")\ntest_dataset = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Read data\nX_train = train_dataset.iloc[:, 1:].values.astype(\"float32\")\nY_train = train_dataset.iloc[:, 0].values.astype(\"int32\")\nX_test = test_dataset.iloc[:, 1:].values.astype(\"float32\")\nNumberID = test_dataset.iloc[:, 0].values.astype(\"float32\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape for CNN\nX_train = X_train.reshape(-1, 28, 28, 1)\nX_test = X_test.reshape(-1, 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Feature Scaling\nX_train /= 255.0\nX_test /= 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# One hot encoding\nY_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Divide the dataset into training and validation\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state = 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Setting hyperparemeters\nepochs = 50\nbatch_size = 64\ninput_dim = (28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Model architecture (normal)\nmodel = Sequential([\n    Conv2D(32, (3, 3), padding = 'same', activation = 'relu', input_shape = input_dim),\n    BatchNormalization(),\n    Conv2D(32, (3, 3), padding = 'same', activation = 'relu'),\n    BatchNormalization(),\n    MaxPool2D(2, 2),\n    Dropout(0.2),\n    Conv2D(64, (3, 3), padding = 'same', activation = 'relu'),\n    BatchNormalization(),\n    Conv2D(64, (3, 3), padding = 'same', activation = 'relu'),\n    BatchNormalization(),\n    MaxPool2D(2, 2),\n    Dropout(0.3),\n    Conv2D(128, (3, 3), padding = 'same', activation = 'relu'),\n    BatchNormalization(),\n    Conv2D(128, (3, 3), padding = 'same', activation = 'relu'),\n    BatchNormalization(),\n    MaxPool2D(2, 2),\n    Dropout(0.4),\n    Flatten(),\n    #Dense(512, activation = 'relu'),\n    #Dropout(0.25),\n    Dense(10, activation = 'softmax')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data Augmentation\ndatagen = ImageDataGenerator(rotation_range = 10,  \n                             zoom_range = 0.1, \n                             width_shift_range = 0.1, \n                             height_shift_range = 0.1,  \n                             horizontal_flip = False, \n                             vertical_flip = False)\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Early Stopping\nearly_stopping = EarlyStopping(monitor = 'val_acc',\n                               patience = 10,\n                               verbose = 1,\n                               mode = 'auto',\n                               restore_best_weights = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reduce LR\nlearning_rate_reduction = ReduceLROnPlateau(monitor = 'val_acc', \n                                            patience = 3, \n                                            verbose = 1, \n                                            factor = 0.5, \n                                            min_lr = 0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"# With data augmentation on training set\nhistory = model.fit_generator(datagen.flow(X_train,Y_train, batch_size = batch_size),\n                              epochs = epochs,\n                              steps_per_epoch = X_train.shape[0] // batch_size,\n                              validation_data = (X_val, Y_val), \n                              callbacks = [learning_rate_reduction, early_stopping])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Submitting Predictions to Kaggle\npreds = model.predict_classes(X_test)\n\ndef write_preds(preds, fname):\n    pd.DataFrame({\"id\": np.arange(preds.shape[0]), \"label\": preds}).to_csv(fname, index=False)\n\nwrite_preds(preds, \"submission.csv\")","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}