{"cells":[{"metadata":{"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 in \nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport cv2\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\nimport random\nimport os,shutil\n\nsrc_path=\"../input\"\n\nprint(os.listdir(src_path))\n\n#constant value\nVALID_SPIT=0.2\nIMAGE_SIZE=80","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label=[]\ndata=[]\ncounter=0\npath=\"../input/train/train\"\nfor file in os.listdir(path):\n    image_data=cv2.imread(os.path.join(path,file), cv2.IMREAD_COLOR)\n    image_data=cv2.resize(image_data,(IMAGE_SIZE,IMAGE_SIZE))\n    if file.startswith(\"cat\"):\n        label.append(0)\n    elif file.startswith(\"dog\"):\n        label.append(1)\n    try:\n        data.append(image_data/255)\n    except:\n        label=label[:len(label)-1]\n    counter+=1\n    if counter%1000==0:\n        print (counter,\" image data retreived\")\n\ndata=np.array(data)\ndata=data.reshape((data.shape)[0],(data.shape)[1],(data.shape)[2],3)\nlabel=np.array(label)\nprint (data.shape)\nprint (label.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_data, valid_data, train_label, valid_label = train_test_split(\n    data, label, test_size=0.2, random_state=42)\nprint(train_data.shape)\nprint(train_label.shape)\nprint(valid_data.shape)\nprint(valid_label.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom keras import applications\n\ninception_model = applications.InceptionV3(weights='imagenet',\n                               include_top=False,\n                               pooling='avg',\n                               input_shape=(80, 80, 3))\n\n\ninception_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom keras import layers\nfrom keras import models\nmodel = models.Sequential()\nmodel.add(inception_model)\n\n\n\nmodel.add(layers.Dense(256, activation  = 'relu'))\nmodel.add(layers.Dense(1, activation = 'sigmoid'))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import backend as K\nK.set_image_dim_ordering('th')\nK.set_image_data_format('channels_last')\nfrom keras import layers\nfrom keras import models\nfrom keras import optimizers\nfrom keras.layers import GlobalAveragePooling2D\n\nmodel.compile(loss='binary_crossentropy',optimizer=optimizers.adam(lr=1e-4),metrics=['acc'])\n# vgg_model.summary()\n# train_history=vgg_model.fit(train_data,train_label,validation_data=(valid_data,valid_label),epochs=40,batch_size=BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"VALID_SPIT=0.2\nIMAGE_SIZE=80\nBATCH_SIZE=20\n\ntrain_history=model.fit(train_data,train_label,validation_data=(valid_data,valid_label),epochs=20,batch_size=BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nacc = train_history.history['acc']\nval_acc = train_history.history['val_acc']\nloss = train_history.history['loss']\nval_loss = train_history.history['val_loss']\nepochs = range(1, len(acc) + 1)\nplt.plot(epochs, acc, 'blue', label='Training acc')\nplt.plot(epochs, val_acc, 'red', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()\nplt.plot(epochs, loss, 'blue', label='Training loss')\nplt.plot(epochs, val_loss, 'red', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import Sequential\nfrom keras.layers import *\nimport keras.optimizers as optimizers\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import *\nimport keras.backend as K\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_directory(\"../input/test1\",target_size=(80, 80),batch_size=32,class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.python.keras.models import Sequential\nfrom keras.models import load_model\n\nprint(\"-- Evaluate --\")\n\nscores = model.evaluate_generator(\n            test_generator, \n            steps = 100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_pred = model.predict(valid_data)\npredicted_label=np.round(Y_pred,decimals=2)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\nfrom mlxtend.plotting import plot_confusion_matrix\n\n# Get the confusion matrix\n\nCM = confusion_matrix(valid_label, Y_pred.round())\nfig, ax = plot_confusion_matrix(conf_mat=CM ,  figsize=(12, 12))\nplt.xticks(range(2), ['Cat', 'Dog'], fontsize=16)\nplt.yticks(range(2), ['Cat', 'Dog'], fontsize=16)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"correct_indices = []\nincorrect_indices = []\n\n# separate the correctly predicted results with incorrectly predicted ones\nfor i in range(len(Y_pred)):\n    if Y_pred.round()[i] == valid_label[i]:\n        correct_indices.append(valid_data[i])\n    else:\n        incorrect_indices.append(valid_data[i])\n\ncorrect_indices = np.array(correct_indices)\nincorrect_indices = np.array(incorrect_indices)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(incorrect_indices)):\n    plt.imshow(incorrect_indices[i])\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(incorrect_indices)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}