{"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=64\nBATCH_SIZE=128\n\n\n# Any results you write to the current direc\n\n# Any results you write to the current directory are saved as output.","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":"ea06bb9d480974907dc9afa84adf6be682248166"},"cell_type":"code","source":"sns.countplot(label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"062d5b7b5e782087a3907d0eb005909f6bafff68"},"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":"e567c34efff96ed3007a537b722b0e44f0053cb8"},"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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f824b3ff9ea2649d54bea73d7d2c9b3ec3c782d1"},"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 = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu',input_shape=(64, 64, 3)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n\nmodel.add(GlobalAveragePooling2D())\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',optimizer=optimizers.adam(lr=1e-4),metrics=['acc'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b4348f8bfa9cc12de09b8723fff15c29edb39380"},"cell_type":"code","source":"callack_saver = ModelCheckpoint(\n            \"model.h5\"\n            , monitor='val_loss'\n            , verbose=0\n            , save_weights_only=True\n            , mode='auto'\n            , save_best_only=True\n        )\n\ntrain_history=model.fit(train_data,train_label,validation_data=(valid_data,valid_label),epochs=40,batch_size=BATCH_SIZE, callbacks=[callack_saver])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fb4e52504693a8a05362e4c09302524dc2f28968"},"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()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0d2225c16ce2e23118f06dbcdcc0be8175acaf87"},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_directory(\"../input/test1\",target_size=(64, 64),batch_size=32,class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"511f00332984086fcca6402cc7bb84f614bb7c10"},"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)\n\nprint(\"%s: %.2f%%\" %(model.metrics_names[1], scores[1]*100))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fd307e1cfa6372542980636a322869e9b256a45a"},"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":"a691ab57016d7c76ba957acb59e2b29b6d3e539c"},"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":"376a901122a0b494dcd6efed2751aab5cadbacbe"},"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":"3c72c13fea7b68517f09919601a08db50d7813cd"},"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":"e674d3dee2431977535247904117e59844c649ed"},"cell_type":"code","source":"dataframe_output[\"label\"]=labels\nprint(dataframe_output)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3f4d36e0634d8c3096734d547827fd6735ccfdc9"},"cell_type":"code","source":"#0이 고양이 1이 강아지\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfor i in range(20):\n    plt.figure()\n    plt.imshow(test_data[i])\n#     plt.xlabel('label')\n    plt.xlabel(dataframe_output[\"label\"][i])\n\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4fc0e8ffe50f0f7b642dca28fc9f01ac1916d2ba"},"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}