{"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 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\nBATCH_SIZE=20","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","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,"_uuid":"6fce09419e64d9055701998272edf388b1acbee9"},"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,"_uuid":"16d321a20f5621b2af3979a63f9ce551d9612509"},"cell_type":"code","source":"from keras import applications\nvgg_model = applications.VGG16(weights='imagenet',\n                               include_top=False,\n                               input_shape=(80, 80, 3))\n\nvgg_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"af1c8f9fedf7ba464d4c4a77bda30f91b81eff99"},"cell_type":"code","source":"from keras import layers\nfrom keras import models\nmodel = models.Sequential()\nmodel.add(vgg_model)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256, activation  = 'relu'))\nmodel.add(layers.Dense(1, activation = 'sigmoid'))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c06c2c5c6ffe0b76e552c804bc1bc006a2205c00"},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b58697d968f0d6827e376295663d43cd8371fd86"},"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,"_uuid":"ee6a15b8da0b3d97504507dd60379618a1e2dd76"},"cell_type":"code","source":"\n\ntrain_history=model.fit(train_data, train_label, epochs=20, batch_size=BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"239fba2b5b726e9c917e9ff68c9fbf1d2d4ba0b5"},"cell_type":"code","source":"Y_pred = model.predict(valid_data)\npredicted_label=np.round(Y_pred,decimals=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2b77896b3e24d7742c063eafdf87e8bc6d7f1459"},"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,"_uuid":"d5278bedd8eca22b40ec7ff36a9ccdde0ac2570d"},"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\n\n\nfrom tensorflow.python.keras.models import Sequential\nfrom keras.models import load_model\n\nprint(\"-- Evaluate --\")\n\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')\nscores = model.evaluate_generator(\n            test_generator, \n            steps = 100)\n\nprint(\"%s: %.2f%%\" %(model.metrics_names[1], scores[1]*100))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5b74e1b06e3075818ed13ca6433147deec45e974"},"cell_type":"code","source":"test_data=[]\nid=[]\ncounter=0\nfor file in os.listdir(\"../input/test1/test1\"):\n    image_data=cv2.imread(os.path.join(\"../input/test1/test1\",file), cv2.IMREAD_COLOR)\n    try:\n        image_data=cv2.resize(image_data,(IMAGE_SIZE,IMAGE_SIZE))\n        test_data.append(image_data/255)\n        id.append((file.split(\".\"))[0])\n    except:\n        print (\"ek gaya\")\n    counter+=1\n\n\n\ntest_data=np.array(test_data)\nprint (test_data.shape)\ntest_data=test_data.reshape((test_data.shape)[0],(test_data.shape)[1],(test_data.shape)[2],3)\ndataframe_output=pd.DataFrame({\"id\":id})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bd90b6926f69f97dd4a6d613eb1c73d56389aff4"},"cell_type":"code","source":"predicted_labels=model.predict(test_data)\npredicted_labels=np.round(predicted_labels,decimals=2)\nlabels=[1 if value>0.5 else 0 for value in predicted_labels]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"de65454e3dfb40a7b359996c8d7dda0e0e4de78c"},"cell_type":"code","source":"dataframe_output[\"label\"]=labels\nprint(dataframe_output)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f86d4c1521bd31100e4e4cd2dc63b40f33b757ce"},"cell_type":"code","source":"#0이 고양이 1이 강아지\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfor i in range(40):\n    plt.figure(figsize=(20, 6))\n    plt.subplot(1, 2, 2)\n    plt.imshow(test_data[i])\n#     plt.xlabel('label')\n    plt.xlabel(dataframe_output[\"label\"][i],fontsize=30)\n    plt.title('0-cat,1-dog',fontsize=40)\n    plt.show()\n\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e07a52191a6b58a797bb7a9ef90f0c32cba3ee99"},"cell_type":"code","source":"correct_indices = []\nincorrect_indices = []\n\nanswer=[1,0,1,1,1,1,0,1,1,0,1,1,1,1,1,0,0,0,0,1,1,0,1,0,1,0,0,0,1,1,0,1,1,1,1,0,1,0,0,0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0517541da9b63797497393ac53b0c9ee764ab2ec"},"cell_type":"code","source":"correct_indices=[]\nincorrect_indices=[]\n\nfor i in range(len(answer)):\n  if dataframe_output[\"label\"][i] == answer[i]:\n    correct_indices.append(test_data[i])\n  else:\n    incorrect_indices.append(test_data[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1e2c5815f1833cba8c2ab281a6112c8d6de303f5"},"cell_type":"code","source":"print(len(correct_indices),len(incorrect_indices))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"09527de51eb2ce7c0848174e4d4417116a40e941"},"cell_type":"code","source":"for i in range(len(correct_indices)):\n    plt.figure(figsize=(20, 6))\n    plt.subplot(1,2,1)\n    plt.title('correct',fontsize=40)\n    plt.imshow(correct_indices[i])\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"45b248bed584afd54d143f1bad260c6d539519a4"},"cell_type":"code","source":"for i in range(len(incorrect_indices)):\n    plt.figure(figsize=(20, 6))\n    plt.subplot(1,2,1)\n    plt.title('incorrect',fontsize=40)\n    plt.imshow(incorrect_indices[i])\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c10e4b784da0e386f29c328e0123ca3c88d25b1b"},"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.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}