{"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)\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.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Import the necessary packages"},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import Input, Dense, Dropout, Flatten, add\nfrom keras.layers import Conv2D, Activation, MaxPooling2D\nfrom keras.layers import AveragePooling2D, BatchNormalization\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint\nimport tensorflow as tf\nfrom keras.models import Model\nfrom keras.utils import plot_model\nfrom keras.preprocessing. image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Input, Dense, PReLU, Dropout\nfrom keras.models import Model\nfrom keras.callbacks import LearningRateScheduler, ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom keras.optimizers import SGD, Adam\nimport matplotlib.pyplot as plt\nimport cv2\nfrom PIL import Image\nimport seaborn as sns\nsns.set()\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"EDA"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"%%time\ntrain_data = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')\ntest_data = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"View label distribution"},{"metadata":{"trusted":true},"cell_type":"code","source":"label_values=train_data['label'].value_counts().sort_index()\nplt.figure(figsize=(5,3))\nplt.title(\"Kanada MNIST label distributions\")\nsns.barplot(x=label_values.index, y=label_values)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Converting CSV data into images"},{"metadata":{"trusted":true},"cell_type":"code","source":"img_train = train_data.drop([\"label\"], axis=1).values.reshape(-1, 28, 28, 1).astype('float32')\nimg_label = train_data[\"label\"]\nimg_test = test_data.drop([\"id\"], axis=1).values.reshape(-1, 28, 28, 1).astype('float32')\nprint(\"img_train.shape = \", img_train.shape)\nprint(\"img_label.shape = \", img_label.shape)\nprint(\"img_test.shape = \", img_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"View some sample images"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(10, 10))\nshow_img = 0\nfor idx in range(img_train.shape[0]):\n    plt.subplot(5, 5, show_img + 1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    plt.imshow(img_train[idx].reshape(28, 28), cmap=plt.cm.binary)\n    plt.title(\"label: %d\" % img_label[idx])\n    show_img += 1\n    if show_img % 25 == 0:\n        break","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"build cnn model"},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_model(input_shape=(28, 28, 1), num_classes = 10):\n    input_layer = Input(shape=input_shape)\n    x = Conv2D(32, (3,3), strides=1, padding=\"same\", name=\"conv1\")(input_layer)\n    x = PReLU()(x)\n    x = Conv2D(32, (3,3), strides=1, padding=\"same\", name=\"conv2\")(x)\n    x = PReLU()(x)\n    x = MaxPooling2D(pool_size=(2, 2), name=\"pool2\")(x)\n    x = Conv2D(64, (5,5), strides=1, padding=\"same\", name=\"conv3\")(x)\n    x = PReLU()(x)\n    x = MaxPooling2D(pool_size=(2, 2), name=\"pool3\")(x)\n    x = Conv2D(64, (5,5), strides=1, padding=\"same\", name=\"conv4\")(x)\n    x = PReLU()(x)\n    x = MaxPooling2D(pool_size=(2, 2), name=\"pool4\")(x)\n    x = Conv2D(128, (5,5), strides=1, padding=\"same\", name=\"conv5\")(x)\n    x = PReLU()(x)\n    x = Conv2D(128, (5,5), strides=1, padding=\"same\", name=\"conv6\")(x)\n    x = PReLU()(x)\n    x = Flatten()(x)\n    x = Dense(512, name=\"full1\")(x)\n    x = PReLU()(x)\n    x = Dropout(0.5)(x)\n    x = Dense(num_classes, activation='softmax', name=\"output\")(x)\n    model = Model(inputs=input_layer, outputs=x)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = build_model()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"******split train data to train and test**"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_data = img_train / 255\nY_data = to_categorical(img_label)\nx_train, x_test, y_train, y_test = train_test_split(X_data, Y_data, test_size=0.1)\nprint(\"x_train.shape = \", x_train.shape)\nprint(\"y_train.shape = \", y_train.shape)\nprint(\"x_test.shape = \", x_test.shape)\nprint(\"y_test.shape = \", y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Image Data Augmentation**"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rotation_range=9, \n    zoom_range=0.25, \n    width_shift_range=0.25, \n    height_shift_range=0.25\n)\ntrain_datagen.fit(x_train)\nsgd = SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False)\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience=5, verbose=1, factor=0.5, min_lr=0.00001)\ncheckpoint = ModelCheckpoint(\"bestmodel.model\", monitor='val_accuracy', verbose=1, save_best_only=True)\nearlyStopping = EarlyStopping(monitor='val_accuracy', patience=15, verbose=1, mode='min')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 100\nbatch_size = 64","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"** training model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(\n    train_datagen.flow(x_train, y_train, batch_size=batch_size),\n    steps_per_epoch=x_train.shape[0] // batch_size,\n    epochs=epochs,\n    validation_data=(x_test, y_test),\n    callbacks=[checkpoint, learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.style.use(\"ggplot\")\nplt.figure(figsize=(16, 4))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**test data******"},{"metadata":{"trusted":true},"cell_type":"code","source":"results=model.predict(img_test/255.0)\nresults=np.argmax(results, axis=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"show some predict image"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(10, 10))\nshow_img = 0\nfor idx in range(img_test.shape[0]):\n    plt.subplot(5, 5, show_img + 1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    plt.imshow(img_test[idx].reshape(28, 28), cmap=plt.cm.binary)\n    plt.title(\"predict: %d\" % results[idx])\n    show_img += 1\n    if show_img % 25 == 0:\n        break","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"save to csv file"},{"metadata":{"trusted":true},"cell_type":"code","source":"sub=pd.DataFrame()\nsub['id']=list(test_data.values[0:,0])\nsub['label']=results\nsub.to_csv(\"submission.csv\", index=False)","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}