{"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":"# Loading Data "},{"metadata":{},"cell_type":"markdown","source":"Here, we'll load the data in data frames of pandas."},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_csv = '/kaggle/input/Kannada-MNIST/train.csv'\ntest_csv = '/kaggle/input/Kannada-MNIST/test.csv'\nval_csv = '/kaggle/input/Kannada-MNIST/Dig-MNIST.csv'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(train_csv)\ntest_df = pd.read_csv(test_csv)\nvalid_df = pd.read_csv(val_csv)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Just checking out how does the data frame looks"},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualizing Data\n\nHere, we're seeing how many samples are present there for each number of classes. To avoid any bias by the network, we'll balance the data by augumentation in case there are no approximately equal number of samples per class"},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.distplot(train_df['label'], kde=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Looks like there are exactly equal number of samples per class. Thus, we don't need any data augumentation to overcome biasing."},{"metadata":{},"cell_type":"markdown","source":"# Formatting Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = train_df.drop('label', axis=1).values\ny_train = train_df['label'].values\n\nX_val = valid_df.drop('label', axis=1).values\ny_val = valid_df['label'].values","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Reshaping data in (28, 28, 1) dims"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.reshape(X_train.shape[0], 28, 28)\nX_val = X_val.reshape(X_val.shape[0], 28, 28)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = np.expand_dims(X_train, axis=3)\nX_val = np.expand_dims(X_val, axis=3)\nn_classes = 10 # 0 through 9","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Converting labels to one-hot encoding"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = to_categorical(y_train)\ny_val = to_categorical(y_val)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Increasing number of samples\nUsing ImageDataGenerator here.\nRef: <a href=\"https://www.kaggle.com/shahules/indian-way-to-learn-cnn\"> Link </a>"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_data_gen = ImageDataGenerator(\n        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.1, # Randomly zoom image \n        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_data_gen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_data_gen.fit(X_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.shape)\nprint(y_train.shape)\nprint(X_val.shape)\nprint(y_val.shape)\nimg_shape = (28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model Definition"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Dropout, BatchNormalization, UpSampling2D\nfrom tensorflow.keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Model Ref: <a href=\"https://www.kaggle.com/shahules/indian-way-to-learn-cnn\"> Link </a>"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters=128, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.4))\nmodel.add(BatchNormalization())\n\n\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.4))\nmodel.add(BatchNormalization())\n\nmodel.add(Conv2D(filters=32, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.4))\nmodel.add(BatchNormalization())\n\nmodel.add(UpSampling2D(size=(3, 3), data_format=None, interpolation='nearest'))\n\nmodel.add(Conv2D(filters=16, kernel_size=(2, 2), activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.4))\nmodel.add(BatchNormalization())\n\nmodel.add(Flatten())\n\n\nmodel.add(Dense(128, activation = \"relu\"))\nmodel.add(Dropout(0.4))\n\nmodel.add(Dense(10, activation = \"softmax\"))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit_generator(image_data_gen.flow(X_train, y_train, batch_size=32),\n                   epochs=10,\n                   validation_data=(image_data_gen.flow(X_val, y_val)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame(model.history.history).plot()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Testing on Test Dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test = test_df.drop('id', axis=1).values.reshape(len(test_df), 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict(x_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit_df = pd.DataFrame(columns=['id', 'label'])\nsubmit_df.index.name = 'id'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for index, pred in enumerate(predictions):\n    df = pd.DataFrame({\n        'id': [index],\n        'label': [pred.argmax()]\n    })\n    submit_df = submit_df.append(df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit_df.to_csv('./submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a href='./submission.csv'> Download </a>"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.layers","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualizing the layer"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.models import Model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"layers = [layer.output for layer in model.layers]\nlen(layers)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Choosing any random layer here to viz.\n<br>\nI chose 19th."},{"metadata":{"trusted":true},"cell_type":"code","source":"partial_model = Model(inputs=model.input, outputs=[layers[:19]])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_partial = partial_model.predict(x_test[220].reshape(1, 28, 28, 1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.imshow(predicted_partial[0][0, :, :, 1])\npredicted_partial[0].shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(x_test[0].reshape(28, 28))\n# x_test[0].shape","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}