{"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)\nfrom sklearn.model_selection import StratifiedShuffleSplit\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.\nBASE_DIR = '/kaggle/input/Kannada-MNIST'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = pd.read_csv(f'{BASE_DIR}/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_raw = df_train['label']\ntrain_raw = df_train.drop(['label'], axis=1) / 255.0\n\nsss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=0)\nfor train_index, test_index in sss.split(train_raw, label_raw):\n    train = train_raw.loc[train_index]\n    label = label_raw.loc[train_index]\n    test = train_raw.loc[test_index]\n    test_label = label_raw.loc[test_index]\n\nprint(len(train), len(label), len(test), len(test_label))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = np.array(train).reshape(-1, 28,28, 1)\ntest = np.array(test).reshape(-1, 28,28,1)\nprint(train.shape)\nprint(test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.layers import Conv2D, BatchNormalization, Dense, Dropout, Flatten, MaxPool2D, LeakyReLU\nfrom tensorflow.keras.models import Sequential\n\n#Data augmentation\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\n\ntf.__version__","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(\n   # featurewise_center=True,\n  #  featurewise_std_normalization=True,\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    horizontal_flip=False)\n\ndatagen.fit(train)\nimage_iterator = datagen.flow(train)\nfit,rows = plt.subplots(nrows=1, ncols=4, figsize=(18,18))\nfor row in rows:\n    image = image_iterator.next()[0].astype('float')\n    image = image.reshape(28,28)\n    row.imshow(image, cmap=plt.cm.gray)\n    row.axis('off')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential([\n    Conv2D(32, kernel_size=2, activation=tf.nn.leaky_relu, input_shape=(28,28,1), padding='same'),\n    MaxPool2D(2),\n    BatchNormalization(),\n    LeakyReLU(),\n    \n    Conv2D(64, kernel_size=2, padding='same'),\n    MaxPool2D(2),\n    Flatten(),\n    BatchNormalization(),\n    LeakyReLU(),\n    \n    Dense(128),\n    Dropout(0.2),\n    BatchNormalization(),\n    LeakyReLU(),\n    \n    Dense(256),\n    Dropout(0.2),\n    BatchNormalization(),\n    Dense(10, activation='softmax')\n])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer=tf.keras.optimizers.Nadam(lr=0.001, decay=1e-5)\nmodel.compile(loss=tf.losses.Huber(), optimizer=optimizer, metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categorical_labels = tf.keras.utils.to_categorical(label)\ncategorical_test_labels = tf.keras.utils.to_categorical(test_label)\n\nearlyStop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20)\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5,\n                              patience=5, min_lr=0.00001, verbose=1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#model.fit(train, categorical_labels, validation_split=0.1, callbacks=[earlyStop], epochs=100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit_generator(datagen.flow(train, categorical_labels, batch_size=32),\n                    steps_per_epoch=len(train) // 32,\n                    epochs=1000,\n                    validation_data=(test, categorical_test_labels),\n                    callbacks=[earlyStop, reduce_lr]\n                   )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test = pd.read_csv(f'{BASE_DIR}/test.csv')\ndf_test.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ids = df_test['id']\ndf_test = df_test.drop(['id'], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final_test = np.array(df_test).reshape(-1, 28,28, 1) / 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = model.predict(final_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"allPredictions = []\nfor id, prediction in zip(ids, result):\n    res = np.argmax(prediction)\n    allPredictions.append([id, res])\n    \ndf_predict = pd.DataFrame(allPredictions, columns=['id', 'label'])\n\ndf_predict.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(allPredictions[:5])","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}