{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Convolutional MNIST classification"},{"metadata":{},"cell_type":"markdown","source":"If you are starting with Deeplearning, solving MNIST classification problem is the \"Hello World\" to deep-learning! This is an attempt to put in practice follwoing neural networks using MNIST dataset:\n* Convolution neural networks (CNN)\n* VGG-16\n* AlexNet\n\nFirst, let us implement CNN on MNIST classification problem,\n\n"},{"metadata":{},"cell_type":"markdown","source":"### Required libraries\nHere, _numpy_ and _pandas_ will help us handle simple mathematical operations and dataframe manipulations. \nIn addition, we will use _tensofrlow.keras_ to define, train, evaluate, and moinotor CNN model. In addition, we will also use it for making predicitons for submission to the KAGGLE'S board.  "},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.layers import Flatten, Conv2D, MaxPooling2D\nfrom sklearn.model_selection import train_test_split\nimport os\n\nimport matplotlib.pyplot as plt\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Following line of code check all the files available in \"../input/Kannada-MNIST/\". i.e.\nWe have following files:\n* train.csv (comprises of 60,000 hand-written digits)\n* test.csv (comprises of 10,000 hand-written digits), and \n* sample_submission.csv ( a submission format comprising of dummy list of ids and labels. We need to replace, the entries with our predictions after designing and training our MNIST-CNN model.)\n"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"print(os.listdir(\"../input/Kannada-MNIST/\"))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Below line of code reads the _train.csv_ and _test.csv_ data files and stores them in dataframes i.e. _df_train_ and _df_test_. "},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = pd.read_csv(\"../input/Kannada-MNIST/train.csv\")\ndf_test = pd.read_csv(\"../input/Kannada-MNIST/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let us check size of train and test data. Train and test data have 785 columns with 60K and 5K entires."},{"metadata":{"trusted":true},"cell_type":"code","source":"print(df_train.shape)\nprint(df_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Here, checking first 5 rows of train and test dataset. Train dataset has the _label_ in the 1st column which we will use as target label while training. "},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let us store the pixels columns in variable \"X\" . and store the label in variable \"y\". Additionally, let us store the test pixels in \"X_test_actual\"; this we will use it to predict. "},{"metadata":{"trusted":true},"cell_type":"code","source":"X = df_train.iloc[:,1:]\ny = df_train.iloc[:,0]\nX_test_actual = df_test.iloc[:,1:]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Sample digits\nWe saw both train and test data has 784 pixels. Each row entry here, represents a digit. i.e. A single digit has 28 x 28 pixel distributed in 2D plane. However, for analysis purpose the pixels were flattened into 1D array i.e. 28 x 28 = 784 pixels ( columns). \n\nLet us visualize some of the hand-written digitized pixels. \n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"data = np.matrix(X) # Convert the dataframe to matrix for visualization","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We have use numpy.reshape() function to reshape the 784 1-D array to 2-D matrix."},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"print(X)# 1-D matrix","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(data) # 2-D matrix","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let us see the kannada words stored in the following rows out of 60000:\n* 1st row kannada digit\n* 25th row Kannada digit\n* 50th row kannada digit"},{"metadata":{"trusted":true},"cell_type":"code","source":"img = data[0].reshape(28,28)\nplt.imshow(img, cmap=\"gray\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = data[24].reshape(28,28)\nplt.imshow(img, cmap=\"gray\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = data[49].reshape(28,28)\nplt.imshow(img, cmap=\"gray\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"* **Given, no literal awareness about kannada digits; it is not possible to recognize the digits 1st, 25th, and 50th represents.** However, we do have the lables from the dataframe df_train. Let us print the 1st, 25th, and 50th row labels showing the actual numeric digits these image represent:\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"print(df_train.iloc[[0,24,49],0])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"NOTE: From the above, it can be concluded that the images shows earlier from the pixels of 1st, 25th, and 50th rows are 0, 4, and 9 respectively. "},{"metadata":{},"cell_type":"markdown","source":"## Data prepration"},{"metadata":{"trusted":true},"cell_type":"code","source":"#X_train.head()\n#_train\n#X_test\n#len(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X.to_numpy().reshape(len(X), 28, 28,1).astype('float32')\nX_test_actual = X_test_actual.to_numpy().reshape(len(X_test_actual), 28, 28, 1).astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X/255\nX_test_actual = X_test_actual/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_classes=10\ny = to_categorical(y, n_classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train,  y_test = train_test_split(X, y, test_size=0.3, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Architecture of neural netrowk "},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=(28,28,1)))\n\nmodel.add(Conv2D(32, kernel_size=(3,3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, kernel_size=(3,3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\n#model.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(n_classes, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy',\n             optimizer='nadam',\n             metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(X_train, \n                    y_train, \n                    batch_size=128, \n                    epochs=100,\n                    verbose=1,\n                    validation_data=(X_test, y_test)\n                   )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(loss) + 1)\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.clf()                                              \n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict(X_test_actual)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df = df_test.iloc[:,0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_submission = pd.read_csv(\"../input/Kannada-MNIST/sample_submission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pre=model.predict(X_test_actual)     ##making prediction\ny_pre=np.argmax(y_pre,axis=1) ##changing the prediction intro labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_submission['label']=y_pre\ndata_submission.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_submission.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}