{"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 \n\nimport numpy as np # linear algebra\nimport 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 all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport os, zipfile, random\n\n# Import the backend\nimport tensorflow as tf\n\n# Data preprocessing\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.utils import to_categorical\n\n# Model architecture\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization\nfrom tensorflow.keras.callbacks import LearningRateScheduler, EarlyStopping, ReduceLROnPlateau\n\n# Model evaluation\nfrom sklearn.metrics import accuracy_score\nimport os, cv2, re, random","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_size = (150, 150)\ninput_dim = (150, 150, 3)\nepochs = 30\nbatch_size = 16","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"local_zip_train = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip'\nlocal_zip_test = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip'\nzip_ref = zipfile.ZipFile(local_zip_train, 'r')\nzip_ref.extractall('/kaggle/working')\nzip_ref.close()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nlocal_zip_train = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip'\nlocal_zip_test = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip'\nzip_ref = zipfile.ZipFile(local_zip_train, 'r')\nzip_ref.extractall('/kaggle/working')\nzip_ref.close()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nfilenames = os.listdir(\"/kaggle/working/train\")\ndogs = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        dogs.append(1)\n    else:\n        dogs.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'dogs': dogs\n})\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_list = []\nfor i in df['filename']:\n    i='/kaggle/working/train/'+i\n    images_list.append(i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_width = 150\nimg_height = 150\ndef prepare_data(list_of_images):\n    \"\"\"\n    Returns two arrays: \n        x is an array of resized images\n        y is an array of labels\n    \"\"\"\n    x = [] # images as arrays\n    y = np.array(df['dogs']) # labels\n   # y1= []\n   # prepared_images=[]\n    \"\"\"  for i in list_of_images:\n        image = load_img(i, target_size=(150, 150))\n        image = img_to_array(image)\n        image = image.reshape((150,150, 3))\n        x.append(preprocess_input(image)) \"\"\"\n    for image in list_of_images:\n        x.append(cv2.resize(cv2.imread(image), (img_width,img_height), interpolation=cv2.INTER_CUBIC))\n        \n  #  for i in x:\n    #    prepared_images.append(preprocess_input(i))\n    \n    return x, y\n    \n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.applications.vgg16 import preprocess_input\nfrom keras.applications.vgg16 import decode_predictions\nfrom keras.layers import Dense, Flatten, Dropout, Lambda, Input, Concatenate, concatenate\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X,Y = prepare_data(images_list) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import random as rn\n\nfig,ax=plt.subplots(5,2)\nfig.set_size_inches(15,15)\nfor i in range(5):\n    for j in range (2):\n        l=rn.randint(0,len(Y))\n        ax[i,j].imshow(X[l])\n        if Y[l]==0 :\n            ax[i,j].set_title(' Cat ')\n        else :\n            ax[i,j].set_title(' Dog ')\n        \n        \nplt.tight_layout()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, Y_train, Y_val = train_test_split(np.array(X),Y, test_size=0.2, random_state=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nfrom keras import backend\nfrom keras.applications.inception_v3 import InceptionV3,preprocess_input\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import SGD\nfrom keras.models import Model, load_model\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping,ModelCheckpoint,TensorBoard\n#Prepare call backs\nLR_callback = keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy', patience=3, verbose=2, factor=.5, min_lr=.00001)\nEarlyStop_callback = keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=7, restore_best_weights=True)\nmy_callback=[EarlyStop_callback, LR_callback]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"InceptionV3_base_model = InceptionV3(weights='imagenet', include_top=False)\nx = InceptionV3_base_model.output\nx_pool = GlobalAveragePooling2D()(x)\nx_poole = Dropout(0.4)(x_pool)\nfinal_predect = Dense(1,activation='sigmoid')(x_poole)\nmodel = Model(inputs=InceptionV3_base_model.input,outputs=final_predect)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"layer_to_Freeze=276    \nfor layer in model.layers[:layer_to_Freeze]:\n    layer.trainable =False\nfor layer in model.layers[layer_to_Freeze:]:\n    layer.trainable=True\n\nsgd = SGD(lr = 0.01, decay = 1e-6, momentum = 0.9, nesterov = True)\n\n\n#model.compile(optimizer=sgd,loss='categorical_crossentropy',metrics=['accuracy'])\n\n\nmodel.compile(optimizer=sgd,loss='binary_crossentropy',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_train_samples = len(X_train)\nnb_validation = len(X_val)\nbatch_size = 50","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1. / 255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True)\n\nval_datagen = ImageDataGenerator(    rescale=1. / 255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_datagen.flow(np.array(X_train), Y_train, batch_size=batch_size)\nvalidation_generator = val_datagen.flow(np.array(X_val), Y_val, batch_size=batch_size)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_transfer_learning = model.fit_generator(train_generator,epochs=20,\n                                                steps_per_epoch=nb_train_samples//batch_size,\n                                                validation_data=validation_generator,\n                                                validation_steps=nb_validation//batch_size,\n                                                verbose=1,\n                                                callbacks=my_callback)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(2,1)\nax[0].plot(history_transfer_learning.history['loss'], color='b', label=\"Training loss\")\nax[0].plot(history_transfer_learning.history['val_loss'], color='r', label=\"validation loss\",axes =ax[0])\nlegend = ax[0].legend(loc='best', shadow=True)\n\nax[1].plot(history_transfer_learning.history['accuracy'], color='b', label=\"Training accuracy\")\nax[1].plot(history_transfer_learning.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nlegend = ax[1].legend(loc='best', shadow=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_pred = model.predict(np.array(X_val))\nfor i in range(0,5):\n    if Y_pred[i] >= 0.5: \n        print('I am  sure this is a Dog')\n    else: \n        print('I am  sure this is a Cat')\n        \n    plt.imshow(X_val[i])    \n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def prepare_data_test(list_of_images):\n\n    x = [] # images as arrays\n    for image in list_of_images:\n        x.append(cv2.resize(cv2.imread(image), (150,150), interpolation=cv2.INTER_CUBIC))\n        return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"local_zip_test = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip'\nzip_ref = zipfile.ZipFile(local_zip_test, 'r')\nzip_ref.extractall('/kaggle/working')\nzip_ref.close()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = os.listdir(\"/kaggle/working/test\")\ncategories = []\nfor filename in filenames:\n    categories.append(filename)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_list = []\nfor i in categories:\n    i='/kaggle/working/test/'+i\n    images_list.append(i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_image=prepare_data_test(images_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_generator = test_datagen.flow(np.array(test_image), batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nprediction_probabilities = model.predict_generator(test_generator, verbose=1,steps = 12500)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"prediction_probabilities","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df = pd.read_csv('/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv')\nfor i, fname in enumerate(categories):\n    index = int(fname[fname.rfind('/')+1:fname.rfind('.')])\n    submission_df.at[index-1, 'label'] = prediction_probabilities[i]\nsubmission_df.to_csv('submission.csv', index=False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = model.evaluate_generator(validation_generator,steps=len(validation_generator))\nprint('Test score:', score[0])\nprint('Test accuracy:', score[1])","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}