{"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\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":{"trusted":true},"cell_type":"code","source":"import keras\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom keras.layers import Dropout\nfrom keras.datasets import cifar10\n\nimport matplotlib.pyplot as plt ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# loading  the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"(X_train, y_train), (X_test, y_test) = cifar10.load_data()\n\nprint('Shape of training data and labels are - ',X_train.shape,y_train.shape)\nprint('Shape of test data and labels are - ',X_test.shape,y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# lets look at training data into much more detail \nprint('Nummber of images - ',X_train.shape[0])\nprint('Dimensions of an image - ',X_train.shape[1:3])\nprint('Number of channels - ',X_train.shape[-1])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Therefore, the training data contains 50000 images, where each image is a 32*32 pixeled and having 3 channels (R,G,B)"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# visualizing an image as three separate channels"},{"metadata":{},"cell_type":"markdown","source":"the single image is 32*32 pixels and has three channels (R,G,B), now, lets separate out the channels and view how the three channels look like\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_channels(img):\n    plt.imshow(img)\n    plt.title('Original image')\n    plt.xticks([])\n    plt.yticks([])\n    plt.show()\n    \n    red_channel = img[:,:,0]\n    green_channel = img[:,:,1]\n    blue_channel = img[:,:,2]\n    \n    fit,ax = plt.subplots(1,3,figsize = (12,6))\n    ax[0].imshow(red_channel,cmap = 'Reds')\n    ax[0].set_title('Red Channel')\n    ax[1].imshow(green_channel,cmap = 'Greens')\n    ax[1].set_title('Green Channel')\n    ax[2].imshow(blue_channel,cmap = 'Blues')\n    ax[2].set_title('Blue channel')\n    for i in range(3):\n        ax[i].set_xticks([])\n        ax[i].set_yticks([])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"idx = np.random.randint(50000)\nshow_channels(X_train[idx])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Lets now look at data classes"},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = ['Airplane', 'Automobile', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck']\nsample = np.random.choice(np.arange(50000),10) #to get random indices\n \n\nfig, axes = plt.subplots(2, 5, figsize=(12,4))\naxes = axes.ravel()\n\nfor i in range(10):\n    idx = sample[i]\n    axes[i].imshow(X_train[idx])\n    axes[i].set_title(labels[y_train[idx][0]])\n    axes[i].axis('off')\n    plt.subplots_adjust(wspace=1)\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Preprocessing"},{"metadata":{"trusted":true},"cell_type":"code","source":"# normalizing the data\nX_train = X_train / 255\nX_test = X_test / 255 ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#one hot encoding\nnum_classes = 10\ny_train = keras.utils.to_categorical(y_train,10)\ny_test = keras.utils.to_categorical(y_test,10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model - 1 - Flatten"},{"metadata":{"trusted":true},"cell_type":"code","source":"len_flatten = np.product(X_train.shape[1:])\nX_train_flatten = X_train.reshape(X_train.shape[0],len_flatten)\nX_test_flatten = X_test.reshape(X_test.shape[0],len_flatten)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train_flatten.shape,y_train.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Dense(units=1024, activation='relu', input_shape=(len_flatten,)))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=512, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=128, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=32, activation='relu'))\nmodel.add(Dense(units=num_classes, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=\"adam\", loss='categorical_crossentropy', metrics=['accuracy'])\n\nhistory = model.fit(X_train_flatten, y_train, epochs=50, validation_split=.3)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['training', 'validation'], loc='best')\nplt.show()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"_,test_acc = model.evaluate(X_test_flatten, y_test)\nprint('Test accuracy is ',test_acc)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model 2 - converting it to grayscale by mean"},{"metadata":{},"cell_type":"markdown","source":"We have seen earlier that the image in colored format has three chaneels, R G and B. To convert it to a single channel we will take mean of the all three channels, so the three channels will have equal contribution to the final image"},{"metadata":{"trusted":true},"cell_type":"code","source":"# now lets apply this function to get the \nX_train_g1 = np.mean(X_train, -1)\nX_test_g1 = np.mean(X_test,-1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Lets again look at the first image"},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_org_and_modified(org,mod):\n    fig,ax = plt.subplots(1,2,figsize = (8,16))\n    ax[0].imshow(org)\n    ax[0].set_title('original image')\n    ax[1].imshow(mod,cmap='Greys')\n    ax[1].set_title('grey scaled')\n\n    ax[0].axis('off')\n    ax[1].axis('off')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"idx = np.random.randint(50000)\nshow_org_and_modified(X_train[idx],X_train_g1[idx])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len_flatten = np.product(X_train_g1.shape[1:])\nX_train_g1 = X_train_g1.reshape(X_train_g1.shape[0],len_flatten)\nX_test_g1 = X_test_g1.reshape(X_test_g1.shape[0],len_flatten)\n\nprint('Shape of data is - ')\nprint(X_train_g1.shape,y_train.shape)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Dense(units=512, activation='relu', input_shape=(len_flatten,)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(units=256, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=128, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=64, activation='relu'))\n\nmodel.add(Dense(units=32, activation='relu'))\nmodel.add(Dense(units=num_classes, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=\"adam\", loss='categorical_crossentropy', metrics=['accuracy'])\n\nhistory = model.fit(X_train_g1, y_train, epochs=50, validation_split=.3)\n\n\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['training', 'validation'], loc='best')\nplt.show()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"_,test_acc = model.evaluate(X_test_g1, y_test)\nprint('Test accuracy is ',test_acc)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Method -3 - Converting to Grayscale  "},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train_g2 = np.dot(X_train[...,:3], [0.299, 0.587, 0.114])\nX_test_g2 = np.dot(X_test[...,:3], [0.299, 0.587, 0.114])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train_g2.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"idx = np.random.randint(50000)\nshow_org_and_modified(X_train[idx],X_train_g2[idx])","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":false,"trusted":true},"cell_type":"code","source":"len_flatten = np.product(X_train_g2.shape[1:])\nX_train_g2 = X_train_g2.reshape(X_train_g2.shape[0],len_flatten)\nX_test_g2 = X_test_g2.reshape(X_test_g2.shape[0],len_flatten)\n\nprint('Shape of data is - ')\nprint(X_train_g2.shape,y_train.shape)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Dense(units=512, activation='relu', input_shape=(len_flatten,)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(units=256, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=128, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=64, activation='relu'))\n\nmodel.add(Dense(units=32, activation='relu'))\nmodel.add(Dense(units=num_classes, activation='softmax'))\n\nmodel.compile(optimizer=\"adam\", loss='categorical_crossentropy', metrics=['accuracy'])\n\nhistory = model.fit(X_train_g2, y_train, epochs=50, validation_split=.3)\n\n\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['training', 'validation'], loc='best')\nplt.show()\n\n\n\n_,test_acc = model.evaluate(X_test_g2, y_test)\nprint('Test accuracy is ',test_acc)","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":4}