{"cells":[{"metadata":{"trusted":true,"_uuid":"c7163a87c0f8fef43f39225c17785a2c935969ec"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"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 \n\n#import numpy as np # linear algebra\n#import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\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\n\n#import os\n#print(os.listdir(\"../input\"))\n\nimport numpy as np \nimport pandas as pd \nimport cv2 as cv \nimport os\nfrom tqdm import tqdm \n\nimport matplotlib.pyplot as plt\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Dropout\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\n\n########## Extracting the input training data ################################################\n\ntrain_path = '../input/train/'\n\ntest_path = '../input/test1/'\n\ntrain_data = []\ntrain_label = []\n#PATH = os.path.join(train_path)\n#print(PATH)\n\nfor file in tqdm(os.listdir(train_path)): \n    img = cv.imread(os.path.join(train_path,file),cv.IMREAD_GRAYSCALE)\n    new_img = cv.resize(img,(96,96))\n#    plt.imshow(img)\n#    plt.show()\n\n    if file.startswith('cat'):\n        train_label.append(0)\n    elif file.startswith('dog'):\n        train_label.append(1)\n    try: \n        train_data.append(new_img/255)\n    except:\n        train_label = train_label[:len(train_label)-1]\n\nprint(len(np.array(train_label)))\n#print(np.array(train_data))\n\ntraining_data = np.array(train_data)\n\ntraining_label = np.array(train_label)\n\n\ntraining_data = training_data.reshape(training_data.shape[0],training_data.shape[1],training_data.shape[2],1)\n\nprint(training_data.shape)\nprint(training_label.shape)\n\n###############################################################\n######### build the CNN model ##############################  \n\nearly_stopping_monitor = EarlyStopping(patience=2)\n\ncheckpoint = ModelCheckpoint('weights.hdf5',monitor='val_loss',save_best_only=True)\n\ncallbacks_list = [checkpoint]\n\nmodel = Sequential()\n\ninput_shape  = (96,96,1)\n\nmodel.add(Conv2D(filters=64,kernel_size=2,activation='relu',input_shape=(96,96,1),padding='same'))\nmodel.add(Conv2D(filters=64,kernel_size=2,activation='relu',padding='valid',strides=2))\nmodel.add(MaxPool2D(2))\n#model.add(Flatten())\n\nmodel.add(Conv2D(filters=64,kernel_size=2,activation='relu',padding='same'))\nmodel.add(Conv2D(filters=64,kernel_size=2,activation='relu',padding='valid',strides=2))\nmodel.add(MaxPool2D(2))\n\nmodel.add(Conv2D(filters=64,kernel_size=2,activation='relu',padding='valid'))\n\nmodel.add(Flatten())\n\nmodel.add(Dropout(0.3))\n\nmodel.add(Dense(100,activation='sigmoid'))\nmodel.add(Dense(1,activation='sigmoid'))\n\n#model.add(Conv2D(kernel_size=(3,3),filters=32,input_shape=input_shape,activation=\"relu\"))\n#model.add(Conv2D(kernel_size=(3,3),filters=64,activation=\"relu\",padding=\"same\"))\n#model.add(MaxPool2D(pool_size=(5,5),strides=(2,2)))\n#\n#model.add(Conv2D(kernel_size=(3,3),filters=10,activation=\"relu\"))\n#model.add(Conv2D(kernel_size=(3,3),filters=5,activation=\"relu\"))\n#\n#model.add(MaxPool2D(pool_size=(3,3),strides=(2,2)))\n#\n#model.add(Conv2D(kernel_size=(2,2),strides=(2,2),filters=10))\n#\n#model.add(Flatten())\n#\n#model.add(Dropout(0.3))\n\n#model.add(Dense(100,activation=\"sigmoid\"))\n#model.add(Dense(1,activation=\"sigmoid\"))\n\n\nmodel.summary()\n\nmodel.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n\nfitting_history = model.fit(training_data,training_label,validation_split=0.2,epochs=20,batch_size=10,\n                    callbacks=callbacks_list)\n\n\nrun_data = fitting_history.history\n\ntrain_loss = run_data['loss']\nvalidate_loss = run_data['val_loss']\n\ntrain_acc = run_data['acc']\nvalidate_acc = run_data['val_acc'] \n\nepochs = range(1, len(train_loss)+1)\n\nplt.plot(epochs,train_loss,color='blue',label='training')\nplt.scatter(epochs,validate_loss,marker=11,color='blue',label='validation')\nplt.title('Training & Validation Loss')\nplt.legend()\nplt.savefig('figure1.eps')\nplt.close() \n\nplt.plot(epochs,train_acc,color='red',label='training')\nplt.scatter(epochs,validate_acc,marker=11,color='red',label='validation')\nplt.title('Training & Validation accuracy')\nplt.legend()\nplt.savefig('figure2.eps')\nplt.close() \n\n##########################################################################################\n\n################## prediction using the model ###################33\n\ntest_data = []\n\nfor tfile in tqdm(os.listdir(test_path)):\n    test_img = cv.imread(os.path.join(test_path,tfile),cv.IMREAD_GRAYSCALE)\n    try: \n        test_nimg = cv.resize(test_img,(96,96))\n        test_data.append(test_nimg/255)\n    except:\n        print('')\n\n#print(test_data)\n\ntesting_data = np.array(test_data) \n\ntesting_data = testing_data.reshape(testing_data.shape[0],testing_data.shape[1],testing_data.shape[2],1)\n\nprint(testing_data.shape)\n\nmodel.load_weights('weights.hdf5')\n\npredicted_label = model.predict(testing_data)\n\nprint(predicted_label)\n\nlabels = [1 if value>0.5 else 0 for value in predicted_label]\n\nprint(labels)\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","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":false},"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}