{"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_minor":4,"nbformat":4,"cells":[{"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-05T13:31:53.696301Z","iopub.execute_input":"2023-05-05T13:31:53.696955Z","iopub.status.idle":"2023-05-05T13:31:53.711595Z","shell.execute_reply.started":"2023-05-05T13:31:53.696922Z","shell.execute_reply":"2023-05-05T13:31:53.710764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Import all required libraries","metadata":{}},{"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\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom keras.models import Sequential\nfrom keras.layers import InputLayer, Dense, Flatten, Lambda\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import Convolution2D , MaxPooling2D\n","metadata":{"execution":{"iopub.status.busy":"2023-05-05T13:31:53.715178Z","iopub.execute_input":"2023-05-05T13:31:53.715446Z","iopub.status.idle":"2023-05-05T13:32:00.965409Z","shell.execute_reply.started":"2023-05-05T13:31:53.715423Z","shell.execute_reply":"2023-05-05T13:32:00.964453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Load train and test data","metadata":{}},{"cell_type":"code","source":"# create the training & test sets, skipping the header row with [1:]\ntrain = pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")\n\n# Create numpy input data\ntrain_full_X = (train.iloc[:,1:].values).astype('float32') # all pixel values\ntrain_full_y = train.iloc[:,0].values.astype('int32') # only labels i.e targets digits\ntest_X = (test.iloc[:,1:].values).astype('float32')\n\n# Reshape\ntrain_full_X = train_full_X.reshape(train_full_X.shape[0], 28, 28,1)\ntest_X = test_X.reshape(test_X.shape[0], 28, 28,1)","metadata":{"execution":{"iopub.status.busy":"2023-05-05T13:32:00.967132Z","iopub.execute_input":"2023-05-05T13:32:00.967866Z","iopub.status.idle":"2023-05-05T13:32:05.956153Z","shell.execute_reply.started":"2023-05-05T13:32:00.967829Z","shell.execute_reply":"2023-05-05T13:32:05.955214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Preprocessing the digit images","metadata":{}},{"cell_type":"markdown","source":"Feature standardization - Z-score","metadata":{}},{"cell_type":"code","source":"# Z-score\nmean_px = train_full_X.mean().astype(np.float32)\nstd_px = train_full_X.std().astype(np.float32)\n\ndef standardize(x): \n    return (x-mean_px)/std_px","metadata":{"execution":{"iopub.status.busy":"2023-05-05T13:32:05.962197Z","iopub.execute_input":"2023-05-05T13:32:05.962740Z","iopub.status.idle":"2023-05-05T13:32:06.092283Z","shell.execute_reply.started":"2023-05-05T13:32:05.962707Z","shell.execute_reply":"2023-05-05T13:32:06.091393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Designing Convolutional Neural Network Architecture","metadata":{}},{"cell_type":"code","source":"model = Sequential([\n    InputLayer(input_shape=(28,28,1)),\n    #Lambda(standardize, input_shape=(28,28,1)),\n    Convolution2D(32,(3,3), activation='relu'),\n    Convolution2D(32,(3,3), activation='relu'),\n    MaxPooling2D(),\n    Convolution2D(64,(3,3), activation='relu'),\n    Convolution2D(64,(3,3), activation='relu'),\n    MaxPooling2D(),\n    Flatten(),\n    Dense(100, activation='relu'),\n    Dense(10, activation='softmax')\n    ])","metadata":{"execution":{"iopub.status.busy":"2023-05-05T13:32:06.093581Z","iopub.execute_input":"2023-05-05T13:32:06.093985Z","iopub.status.idle":"2023-05-05T13:32:08.516315Z","shell.execute_reply.started":"2023-05-05T13:32:06.093953Z","shell.execute_reply":"2023-05-05T13:32:08.515385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Compile the network","metadata":{}},{"cell_type":"code","source":"optimizer = keras.optimizers.Adam()\nmodel.compile(optimizer=optimizer,\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-05-05T13:32:08.517531Z","iopub.execute_input":"2023-05-05T13:32:08.520261Z","iopub.status.idle":"2023-05-05T13:32:08.822547Z","shell.execute_reply.started":"2023-05-05T13:32:08.520234Z","shell.execute_reply":"2023-05-05T13:32:08.821649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Split the data","metadata":{}},{"cell_type":"code","source":"train_X, val_X, train_y, val_y = train_test_split(train_full_X, train_full_y, test_size=0.10, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2023-05-05T13:32:08.823955Z","iopub.execute_input":"2023-05-05T13:32:08.824289Z","iopub.status.idle":"2023-05-05T13:32:09.301208Z","shell.execute_reply.started":"2023-05-05T13:32:08.824254Z","shell.execute_reply":"2023-05-05T13:32:09.300293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Run the model","metadata":{}},{"cell_type":"code","source":"early_stopping = EarlyStopping(\n    patience=5,\n    min_delta=0.001,\n    restore_best_weights=True,\n)\nhistory = model.fit(\n    train_X, train_y,\n    validation_data=(val_X, val_y),\n    batch_size=512,\n    epochs=200,\n    callbacks=[early_stopping],verbose=1)","metadata":{"execution":{"iopub.status.busy":"2023-05-05T13:32:09.302900Z","iopub.execute_input":"2023-05-05T13:32:09.303401Z","iopub.status.idle":"2023-05-05T13:32:36.677326Z","shell.execute_reply.started":"2023-05-05T13:32:09.303365Z","shell.execute_reply":"2023-05-05T13:32:36.676429Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_df = pd.DataFrame(history.history)\nhistory_df.loc[:, ['loss', 'val_loss']].plot(title=\"Cross-entropy\")\nhistory_df.loc[:, ['accuracy', 'val_accuracy']].plot(title=\"Accuracy\")","metadata":{"execution":{"iopub.status.busy":"2023-05-05T13:32:36.678591Z","iopub.execute_input":"2023-05-05T13:32:36.679396Z","iopub.status.idle":"2023-05-05T13:32:37.443311Z","shell.execute_reply.started":"2023-05-05T13:32:36.679362Z","shell.execute_reply":"2023-05-05T13:32:37.442425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(test_X)\n\noutput = pd.DataFrame({'id': test.id, 'label': np.argmax(predictions, axis=1)})\noutput.to_csv('submission.csv', index=False)\nprint(\"Your submission was successfully saved!\")","metadata":{"execution":{"iopub.status.busy":"2023-05-05T13:32:37.446626Z","iopub.execute_input":"2023-05-05T13:32:37.447437Z","iopub.status.idle":"2023-05-05T13:32:38.045123Z","shell.execute_reply.started":"2023-05-05T13:32:37.447400Z","shell.execute_reply":"2023-05-05T13:32:38.044183Z"},"trusted":true},"execution_count":null,"outputs":[]}]}