{"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":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from 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(X_train.shape,X_test.shape)\nprint(y_train.shape,y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"l_grid,w_grid=15,15\n\nfig,axes=plt.subplots(l_grid,w_grid,figsize=(25,25))\n\naxes=axes.ravel() #used to flatten the image into 25*25\nn_training=len(X_train)\nfor i in np.arange(0,l_grid*w_grid):\n  index=np.random.randint(0,n_training)\n  axes[i].imshow(X_train[index])\n  axes[i].set_title(y_train[index])\n  axes[i].axis('off')\nplt.subplots_adjust(hspace=0.6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train=X_train.astype('float32')\nX_test=X_test.astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\ny_train=keras.utils.to_categorical(y_train,10)\ny_test=keras.utils.to_categorical(y_test,10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train=X_train/255\nX_test=X_test/255\nX_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Input_shape=X_train.shape[1:]\nInput_shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D,MaxPooling2D,AveragePooling2D,Dense,Flatten,Dropout\nfrom keras.optimizers import Adam\nfrom keras.callbacks import TensorBoard","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cnn_model= Sequential()\ncnn_model.add(Conv2D(filters=32,kernel_size=(3,3),activation='relu',input_shape=Input_shape))\ncnn_model.add(Conv2D(filters=32,kernel_size=(3,3),activation='relu'))\ncnn_model.add(MaxPooling2D(2,2))\ncnn_model.add(Dropout(0.25))\n\ncnn_model.add(Conv2D(filters=64,kernel_size=(3,3),activation='relu'))\ncnn_model.add(Conv2D(filters=64,kernel_size=(3,3),activation='relu'))\ncnn_model.add(MaxPooling2D(2,2))\ncnn_model.add(Dropout(0.5))\n\ncnn_model.add(Flatten())\n\ncnn_model.add(Dense(512,activation='relu'))\ncnn_model.add(Dense(512,activation='relu'))\ncnn_model.add(Dense(10,activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cnn_model.compile(loss='categorical_crossentropy',optimizer=keras.optimizers.RMSprop(lr=0.001),metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cnn_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history= cnn_model.fit(X_train,y_train, batch_size =32,epochs=5,shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"evaluation= cnn_model.evaluate(X_test,y_test)\nprint(\"Test Accuracy: {}\".format(evaluation[1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test=y_test.argmax(-1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample=pd.read_csv('/kaggle/input/cifar-10/sampleSubmission.csv')\nsample.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_tes=pd.read_csv('/kaggle/input/cifar-10/trainLabels.csv')\ny_tes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nle= LabelEncoder()\ny_tes['label']=le.fit_transform(y_tes['label'])\ny_tes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_class= cnn_model.predict_classes(X_test)\nfrom sklearn.metrics import confusion_matrix\ncm= confusion_matrix(y_test,predicted_class)\nplt.figure(figsize=(10,10))\nsns.heatmap(cm,annot=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import classification_report\nprint(classification_report(y_test,predicted_class))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_class= le.inverse_transform(predicted_class)\nlabels=np.unique(predicted_class)\nprint(labels)\npredicted_class\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"l,w=7,7\nfig,axes=plt.subplots(l,w,figsize=(15,15))\ny_test=le.inverse_transform(y_test)\naxes=axes.ravel() #used to flatten the image\nn_testing=len(X_test)\nfor i in np.arange(0,l*w):\n    axes[i].imshow(X_test[i])\n    axes[i].set_title(\"Prediction: {}\\n True: {}\".format(predicted_class[i],y_test[i]))\n    axes[i].axis('off')\nplt.subplots_adjust(wspace=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\ndirectory= os.path.join(os.getcwd(),'saved_models')\nif not os.path.isdir(directory):\n    os.makedirs(directory)\nmodel_path=os.path.join(directory,'keras_cifar10.h5')\ncnn_model.save(model_path)","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}