{"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":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport os","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Input\nfrom tensorflow.keras.layers import Activation, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.layers import BatchNormalization","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data=pd.read_csv('../input/Kannada-MNIST/train.csv')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_data= data.values[:600, 1:]\ny_label=data.values[:600, 0]\nn_classes=10\ny_label = to_categorical(y_label, n_classes)\n\nX_data = X_data.reshape((X_data.shape[0], 28, 28, 1))\nfrom sklearn.model_selection import train_test_split\nX_train_pre_process, X_test_pre_process, y_train_pre_process, y_test_pre_process = train_test_split(X_data, y_label ,test_size=0.2, random_state=42)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def data_augment(X_train,y_train, batch_size):\n    from tensorflow.keras.preprocessing.image import ImageDataGenerator # for data augmentation\n\n    datagen = ImageDataGenerator(zoom_range=0.1,\n                                 width_shift_range=0.3,\n                                 height_shift_range=0.3,\n                                 rotation_range=5)\n    datagen.fit(X_data)\n    train_generator=datagen.flow(X_train, y_train, batch_size=32, shuffle=True)\n    i=0\n    for img_batch in train_generator:\n        x,y=img_batch\n        X_train=np.concatenate((X_train,x), axis=0)\n        y_train=np.concatenate((y_train,y), axis=0)\n        i=i+1    \n        if i >= batch_size:\n            break\n    return X_train, y_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train_gray, y_train_gray=data_augment(X_train_pre_process, y_train_pre_process,20)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train_gray.shape)\nprint(y_train_gray.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def gray_rgb(X_data):\n    X=[]\n\n    for i in range(X_data.shape[0]):\n        X_temp=X_data[i,:].reshape(28,28,1)\n        X_temp_resize= tf.image.resize(X_temp, [94,94])\n        X.append(np.concatenate((X_temp_resize,X_temp_resize,X_temp_resize),axis=-1))\n    return X","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train=np.asarray(gray_rgb(X_train_gray))\nX_test=np.asarray(gray_rgb(X_test_pre_process))\n\ny_train=y_train_gray\ny_test=y_test_pre_process","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model=tf.keras.applications.MobileNetV2(\n    input_shape=(94,94,3), alpha=1.0, include_top=False, weights='imagenet',\n    input_tensor=None, pooling=None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential([\n  base_model,\n  tf.keras.layers.Conv2D(32, 3, activation='relu'),\n  tf.keras.layers.Dropout(0.2),\n  tf.keras.layers.GlobalAveragePooling2D(),\n  tf.keras.layers.Dense(10, activation='softmax')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"c=model.fit(x=X_train, y=y_train,epochs=30,batch_size=32, validation_data=(X_test,y_test), shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss = c.history['loss']\nval_loss = c.history['val_loss']\n\nlen(loss)\n\ntrain_epoch=range(1,31)\nplt.plot(train_epoch,loss, label='loss')\nplt.plot(train_epoch,val_loss, label='validation_loss')\n\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"accuracy  = c.history['accuracy']\nval_accuracy = c.history['val_accuracy']\n\n\n\ntrain_epoch=range(1,31)\nplt.plot(train_epoch,accuracy , label='accuracy')\nplt.plot(train_epoch,val_accuracy , label='val_accuracy')\n\nplt.xlabel('Epoch')\nplt.ylabel('accuracy')\nplt.legend()\n\ntext=('best accuracy' ,max(val_accuracy),)\n\n","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}