{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# importing libaries\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\n\nimport seaborn as sns\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# importing dataset\nfrom keras.datasets import cifar10\n(X_train, y_train) , (X_test, y_test) = cifar10.load_data()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(y_train.shape)\nprint(X_train.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train =to_categorical(y_train)\n\ny_test =to_categorical(y_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(32, 32, 3)))\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\n\tmodel.add(Dense(10, activation='softmax'))\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# compile model\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# convert from integers to floats\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\n# normalize to range 0-1\nX_train = X_train / 255.0\nX_test = X_test/ 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# data augumentation\ndatagen = ImageDataGenerator(rotation_range=20,\n                              width_shift_range=0.2,\n                              height_shift_range=0.2,\n                              horizontal_flip=True)\n\ndatagen.fit(X_train)\nflow=datagen.flow(X_train, y_train, batch_size=64)\nsteps = int(len(X_train) / 64)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# fits the model on batches with real-time data augmentation:\n\nhistory=model.fit_generator(flow , steps_per_epoch=steps , epochs=200 , validation_data= (X_test,y_test), verbose=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss, acc = model.evaluate(X_test, y_test, verbose=0)\nprint('%.3f' % (acc * 100.0))\nprint('%.3f' % (loss * 100.0))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# make prediction.\n# on test set\npred = model.predict(X_test)\nprint(pred)\nprint(y_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history.history.keys()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# accuracy plot for image classification\nplt.plot(history.history['accuracy'],color='blue',label='train')\nplt.plot(history.history['val_accuracy'],color='green',label='test')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'],color='blue',label='train')\nplt.plot(history.history['val_loss'],color='green',label='test')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_true = np.argmax(y_test, axis=1)\nY_true","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_pred_class= np.argmax(pred, axis=1) \nY_pred_class","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=pd.read_csv('/kaggle/input/cifar-10/trainLabels.csv')\nlabels['label'].unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# confusion matrix for 10 labels\n\ncm=confusion_matrix(Y_true,Y_pred_class)\nprint(cm)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"names = ['Airplane', 'Automobile', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck']\nfrom sklearn.metrics import confusion_matrix,classification_report\n\nplt.subplots(figsize=(12,12))\n# fmt for integer values\n# cm is values of confusion matrix\n# names for x and y are mentioned\nplt.title('Prediction Count')\nsns.heatmap(cm,xticklabels=names,yticklabels=names,annot=True,fmt='d')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# showing result\n# fixing space for each image\nfig, axes = plt.subplots(4, 6, figsize=(10,10))\n# defining boundary for each image\naxes = axes.ravel()\n\nfor i in np.arange(0, 24):\n    axes[i].imshow(X_test[i])\n    axes[i].set_title(\"True: %s \\nPredict: %s\" % (names[Y_true[i]], names[Y_pred_class[i]]))\n    plt.subplots_adjust(wspace=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"incorrect_pred_idx=np.where(Y_true!=Y_pred_class)[0].tolist()\nincorrect_pred_idx","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig,axes=plt.subplots(4,4,figsize=(10,10))\naxes=axes.ravel()\n\nfor i in np.arange(0,16):\n        axes[i].imshow(X_test[incorrect_pred_idx[i]])\n        axes[i].set_title('True: %s \\n Pred: %s'%(names[Y_true[incorrect_pred_idx[i]]],names[Y_pred_class[incorrect_pred_idx[i]]]))\n        plt.subplots_adjust(wspace=1)\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(classification_report(Y_true, Y_pred_classes))","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}