{"cells":[{"metadata":{},"cell_type":"markdown","source":"This is the another version of already written convolutional neural network but i have made some changes to the layers and the epochs to gain high accuracy\n","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# Libraries \nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport cv2\nfrom PIL import Image\nimport os\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# Reading the input images and putting them into a numpy array\ndata=[]\nlabels=[]\n\nheight = 30\nwidth = 30\nchannels = 3\nclasses = 120\nn_inputs = height * width*channels\ndata_dir = \"../input/dog-breed-identification/\"\nselected_breed_list = list(dogsType.groupby('breed').count().sort_values(by='id', ascending=False).head(classes).index)\n\ndogsType = pd.read_csv(data_dir+ 'labels.csv')\ndogsType = dogsType[dogsType['breed'].isin(selected_breed_list)]\n\n\ndictNameToLabel = {}\ntarget = 0\n\nfor name in selected_breed_list:\n    dictNameToLabel.update({name: target})\n    target+=1\nimagesPath = data_dir + \"train/\"\ninputImages =os.listdir(imagesPath)\nfor imageName in inputImages:\n    try:\n        image=cv2.imread(imagesPath+imageName)\n        image_from_array = Image.fromarray(image, 'RGB')\n        size_image = image_from_array.resize((height, width))\n        data.append(np.array(size_image))\n        imageNameNoSuf = imageName[:-4]\n\n        dogName = (dogsType.loc[dogsType['id']== imageNameNoSuf].breed.values)[0]\n        labels.append(dictNameToLabel[dogName])\n    except AttributeError:\n        print(\" \")\n        \nprint(\"Done reading train files\")        \nCells=np.array(data)\nlabels=np.array(labels)\n\n#Randomize the order of the input images\n\ns=np.arange(Cells.shape[0])\nnp.random.seed(classes)\nnp.random.shuffle(s)\nCells=Cells[s]\nlabels=labels[s]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Spliting the images into train and validation sets\n(X_train,X_val)=Cells[(int)(0.2*len(labels)):],Cells[:(int)(0.2*len(labels))]\nX_train = X_train.astype('float32')/255 \nX_val = X_val.astype('float32')/255\n(y_train,y_val)=labels[(int)(0.2*len(labels)):],labels[:(int)(0.2*len(labels))]\n\n#Using one hote encoding for the train and validation labels\nfrom keras.utils import to_categorical\ny_train = to_categorical(y_train, classes)\ny_val = to_categorical(y_val, classes)\nprint(\"done spliting\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Definition of the DNN model\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout\n\nmodel = Sequential()\nmodel.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:]))\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(rate=0.25))\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(rate=0.25))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dropout(rate=0.5))\nmodel.add(Dense(classes, activation='softmax'))\n\n#Compilation of the model\nmodel.compile(\n    loss='categorical_crossentropy', \n    optimizer='adam', \n    metrics=['accuracy']\n)\nprint(\"Done compilation\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#using ten epochs for the training and saving the accuracy for each epoch\nepochs = 10\nhistory = model.fit(X_train, y_train, batch_size=32, epochs=epochs,\nvalidation_data=(X_val, y_val))\n\n#Display of the accuracy and the loss values\nimport matplotlib.pyplot as plt\n\nplt.figure(0)\nplt.plot(history.history['acc'], label='training accuracy')\nplt.plot(history.history['val_acc'], label='val accuracy')\nplt.title('Accuracy')\nplt.xlabel('epochs')\nplt.ylabel('accuracy')\nplt.legend()\n\nplt.figure(1)\nplt.plot(history.history['loss'], label='training loss')\nplt.plot(history.history['val_loss'], label='val loss')\nplt.title('Loss')\nplt.xlabel('epochs')\nplt.ylabel('loss')\nplt.legend()","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}