{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = '/kaggle/input/Kannada-MNIST/train.csv'\ntest = '/kaggle/input/Kannada-MNIST/test.csv'\n\ndataset = pd.read_csv(train)\ndataset_test = pd.read_csv(test)\ndataset_test = dataset_test.drop(['id'], axis = 1)\n\nfeatures = dataset.drop(['label'], axis = 1)\nlabels = dataset['label']\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"features = features.values\nfeatures_test = dataset_test.values\nprint(features.shape)\nprint(features_test.shape)\n\nfeatures = features.reshape((features.shape[0], 28, 28))\nfeatures_test = features_test.reshape((features_test.shape[0], 28, 28))\n\nprint(features.shape)\nprint(features_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils import np_utils\n\nseed = 300\ntest_size = 0.2\n\n# Import train_test_split\nfrom sklearn.model_selection import train_test_split\n# Split the 'features' and 'labels' data into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(features, labels, test_size = test_size, random_state = seed, stratify=labels)\n#X_test, X_valid, y_train, y_valid = train_test_split(X_test, y_test, test_size = 0.1, random_state = seed)\n\nX_train = np.repeat(X_train[..., np.newaxis], 1, -1)\nX_test = np.repeat(X_test[..., np.newaxis], 1, -1)\nfeatures_test = np.repeat(features_test[..., np.newaxis], 1, -1)\n\ny_train = np_utils.to_categorical(np.array(y_train), 10)\ny_test = np_utils.to_categorical(np.array(y_test), 10)\n\nprint(\"features set has {} samples.\".format(features.shape))\nprint(\"Training set has {} samples.\".format(X_train.shape))\nprint(\"Testing set has {} samples.\".format(X_test.shape))\n#print(\"Valid set has {} samples.\".format(X_valid.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.layers import Dropout, Flatten, Dense, BatchNormalization\nfrom keras.models import Sequential\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters=16, kernel_size=5, padding='same', activation='relu', input_shape=(28, 28, 1)))\nmodel.add(Conv2D(filters=16, kernel_size=5, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(filters=32, kernel_size=5, padding='same', activation='relu'))\nmodel.add(Conv2D(filters=32, kernel_size=5, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(filters=64, kernel_size=5, padding='same', activation='relu'))\nmodel.add(Conv2D(filters=64, kernel_size=5, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.4))\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint  \n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\nWEIGHTS_FILE = 'weights.base.hdf5'\n### TODO: specify the number of epochs that you would like to use to train the model.\n\nepochs = 100\n\n### Do NOT modify the code below this line.\n\ncheckpointer = ModelCheckpoint(filepath='WEIGHTS_FILE', \n                             verbose=1, save_best_only=True)\n\nhistory = model.fit(X_train, \n                  y_train, \n                  validation_data=(X_test, y_test),\n                  epochs=epochs, \n                  batch_size=200, \n                  callbacks=[checkpointer], \n                  verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy\n\ndef plot_history(history):\n    # summarize history for accuracy\n    plt.plot(history.history['accuracy'])\n    plt.plot(history.history['val_accuracy'])\n    plt.title('model accuracy')\n    plt.ylabel('accuracy')\n    plt.xlabel('epoch')\n    plt.legend(['train', 'test'], loc='upper left')\n    plt.show()\n    # summarize history for loss\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('model loss')\n    plt.ylabel('loss')\n    plt.xlabel('epoch')\n    plt.legend(['train', 'test'], loc='upper left')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_history(history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(features_test.shape)\n# get index of predicted dog breed for each image in test set\npredictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in features_test]\n\nprint(np.array(predictions))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm weights.base.hdf5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(np.array(predictions))\npredictions_df = pd.DataFrame(np.array(predictions), columns = ['Label'])\npredictions_df.reset_index(level=0, inplace=True)\npredictions_df.columns = ['id', 'label']\npredictions_df.index += 1 \npredictions_df.to_csv('predictions.csv', index = False)\npredictions_df.head()","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}