{"cells":[{"metadata":{},"cell_type":"markdown","source":"# How to build an Image Classification Model ?\nIn this notebook you will learn to build and train an image classificationmodel with Convolutional Neural Network using Keras api.\n### Steps:\n1. Data Preparation\n2. Define CNN model\n3. Evaluate the model\n4. Prediction","execution_count":null},{"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\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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Importing Libraries","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom sklearn.model_selection import train_test_split\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Lambda, Flatten, Dense\nfrom keras.utils.np_utils import to_categorical \nfrom keras.optimizers import Adam, RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Preparation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Loading Train and Test Data\ntrain = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.set_option('display.max_rows', None)\npd.set_option('display.max_columns', None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = train.drop('label', axis=1)\ny = train['label']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Shape of independent features: ', X.shape)\nprint('Shape of target label: ', y.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(y)\ny.value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Check Missing Values(if any)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Hence, there is no missing value present in the data","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### Normalizing the data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X/255.0\ntest = test/255.0","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Reshape image into 3-dimensions (height=28px, width=28px, channels=1)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X.values.reshape(X.shape[0], 28,28,1)\ntest = test.values.reshape(test.shape[0], 28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X.shape, test.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### One-hot-encoding","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Encode labels to one-hot-vectors (For ex '3' is represented as: [0,0,0,1,0,0,0,0,0,0])\ny = to_categorical(y, num_classes=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Let's look the output\ny","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Train-test-split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Note:\nBe carefull with some unbalanced dataset, a simple random split could cause inaccurate evaluation during the validation. To avoid that, you could use stratify = True option in train_test_split function.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Let's check one of the training image\nplt.imshow(X_train[15][:,:,0], cmap='gray')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Define the model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32, (5,5), padding='Same', activation='relu', input_shape=(28,28,1)))\nmodel.add(Conv2D(32, (5,5),padding = 'Same', activation ='relu'))\n\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3,3), padding='Same', activation='relu'))\nmodel.add(Conv2D(64, (3,3), padding='Same',activation='relu'))\n\nmodel.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25)),\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = 'relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(10, 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":"# Define Optimizer\noptimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-8, decay=0.001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Set learning rate reduction\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy',\n                                           factor=0.5,\n                                           verbose=2,\n                                           min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Data Augmentation\nTo generate more images for training the model ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(rotation_range=20,\n                            zoom_range=0.2,\n                            height_shift_range=0.2,\n                            width_shift_range=0.2,\n                            horizontal_flip=False,\n                            vertical_flip=False)\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_epoch =35\nbatch_size=86","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fit the model\nhistory = model.fit_generator(datagen.flow(X_train, y_train,batch_size=batch_size),\n                             epochs=num_epoch, steps_per_epoch=X_train.shape[0] // batch_size,\n                             validation_data=(X_test, y_test))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the loss and accuracy curves for training and validation \nplt.figure(figsize=(14,6))\nax1 = plt.subplot(1,2,1)\nax1.plot(history.history['loss'], color='b', label='Training Loss') \nax1.plot(history.history['val_loss'], color='r', label = 'Validation Loss',axes=ax1)\nlegend = ax1.legend(loc='best', shadow=True)\nax2 = plt.subplot(1,2,2)\nax2.plot(history.history['accuracy'], color='b', label='Training Accuracy') \nax2.plot(history.history['val_accuracy'], color='r', label = 'Validation Accuracy')\nlegend = ax2.legend(loc='best', shadow=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Confusion Matrix","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"y_prediction = model.predict(X_test)\ny_prediction = np.argmax(y_prediction, axis=1)\ny_true = np.argmax(y_test, axis=1)\n\nimport scikitplot as skplt\nskplt.metrics.plot_confusion_matrix(y_true, y_prediction, title='Confusion Matrix for Validation Data')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Predict the result","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = model.predict(test)\npred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# select the index with the maximum probability\nprediction = np.argmax(pred, axis = 1)\nprediction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"prediction = pd.Series(data=prediction, name='Label')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Save predictions\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),prediction],axis = 1)\n\nsubmission.to_csv(\"Digit_Recognizer_submission09.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"### Give it a try:)\n### Upvote if you like this notebook","execution_count":null}],"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":4}