{"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 ","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import 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 \"../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.\n\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom keras.utils.np_utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, BatchNormalization\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.preprocessing import image\nfrom keras.optimizers import RMSprop,Adam\nfrom keras.callbacks import EarlyStopping, LearningRateScheduler\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"markdown","source":"## 1a.Task :- Image Processing\n                ** The task here is to predict kannada numbers **\n\n## 1b.Source of Competetion : -\n                **Kaggle Play Ground Competetion, deadline 17th Dec 2019**\n\n## 2. Hypothesis on the approach and breif description :-\n\n        **The idea is to use CNN(keras) and fastai.\n        I also want to use data agumentation to increase the data used\n        ** \n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")\nDig_Min = pd.read_csv(\"/kaggle/input/Kannada-MNIST/Dig-MNIST.csv\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def norm_reshape(df):\n    try:\n        df = df.drop('label', axis=1)\n    except:\n        print(\"No label column\")\n    df = df/255\n    df=df.values.reshape(-1,28,28,1)\n    return df\n\ndef plot_acc(history):\n    import matplotlib.pyplot as plt\n    history_dict = history.history\n    acc_values = history_dict['accuracy'] \n    val_acc_values = history_dict['val_accuracy']\n    acc = history_dict['accuracy']\n    epochs = range(1, len(acc) + 1)\n    plt.plot(epochs, acc, 'bo', label='Training acc')\n    plt.plot(epochs, val_acc_values, 'b', label='Validation acc')\n    plt.title('Training and validation accuracy')\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend()\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"\n\n#Dig_Min = pd.read_csv(\"/kaggle/input/Kannada-MNIST/Dig-MNIST.csv\")\n\n## 3. Brief Notes on findings moving on \n\ndata.head()\n\ndata.shape\n\ntest.shape\n\ndata.columns[1:]\n\ndata['label'].value_counts().index\n\nsns.barplot(data['label'].value_counts().index,data['label'].value_counts())\n\n\n\nY_TRAIN = data['label']\n\n#X_TRAIN = data.drop('label', axis=1)\n\n\n#X_TRAIN = X_TRAIN/255\n#Y_TRAIN = Y_TRAIN/255\n\n#X_TRAIN.head()\n\n#X_TRAIN=X_TRAIN.values.reshape(-1,28,28,1)\n\nX_TRAIN = norm_reshape(data)\n\nY_VAL = Dig_Min['label']\nY_VAL = to_categorical(Y_VAL)\n\nX_VAL = norm_reshape(Dig_Min)\n\n\n\n\nX_TRAIN\n\nplt.imshow(X_TRAIN[4][:,:,0])\nprint(Y_TRAIN[4])\n\n\nY_TRAIN = to_categorical(Y_TRAIN)\n\nX_TRAIN.shape\n\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28, 28, 1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size=5, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(128, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, kernel_size=5, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\n\nmodel.add(Conv2D(256, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Flatten())\nmodel.add(Dense(256))\nmodel.add(BatchNormalization())\nmodel.add(Dense(256))\nmodel.add(BatchNormalization())\nmodel.add(Dense(10, activation='softmax'))\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#x_train, x_valid, y_train, y_valid = train_test_split(X_TRAIN, Y_TRAIN, test_size = 0.10, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rotation_range=10,\n                                   width_shift_range=0.25,\n                                   height_shift_range=0.25,\n                                   shear_range=0.1,\n                                   zoom_range=0.25,\n                                   horizontal_flip=False)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"optimizer = Adam(learning_rate=0.0001,beta_1=0.9,beta_2=0.999)\nmodel.compile(loss = 'categorical_crossentropy',optimizer = optimizer,metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#es = EarlyStopping(monitor='val_accuracy', mode='max', min_delta=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"annealer = LearningRateScheduler(lambda x: 1e-3 * 0.90 ** x)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"#history1 = model.fit(X_TRAIN, Y_TRAIN, epochs=20, validation_data=(X_VAL, Y_VAL), batch_size=128, verbose=1, callbacks=[annealer])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history1 = model.fit_generator(train_datagen.flow(X_TRAIN, Y_TRAIN, batch_size=128),\n                              steps_per_epoch=200,\n                              epochs=25,\n                              validation_data=(X_VAL, Y_VAL),\n                              validation_steps=70,\n                              callbacks=[annealer],\n                              verbose=1,)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_acc(history1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")\nsample_sub=pd.read_csv('../input/Kannada-MNIST/sample_submission.csv')\n\n\n\n\n#test = norm_reshape(test)\ntest=test.drop('id',axis=1)\ntest=test/255\ntest=test.values.reshape(-1,28,28,1)\n\ny_pre=model.predict(test)     ##making prediction\ny_pre=np.argmax(y_pre,axis=1) ##changing the prediction intro labels\n\nsample_sub['label']=y_pre\nsample_sub.to_csv('submission.csv',index=False)\n\nsample_sub.head()","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":1}