{"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\n\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 cv2\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport os\nimport random\nimport gc","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir = '/kaggle/input/dogs-vs-cats/train/train'\ntest_dir = '/kaggle/input/dogs-vs-cats/test1/test1'\n\ntrain_dogs=['/kaggle/input/dogs-vs-cats/train/train/{}'.format(i) for i in os.listdir(train_dir) if 'dog' in i]\ntrain_cats=['/kaggle/input/dogs-vs-cats/train/train/{}'.format(i) for i in os.listdir(train_dir) if 'cat' in i]\n\ntest_imgs = ['/kaggle/input/dogs-vs-cats/test1/test1/{}'.format(i) for i in os.listdir(test_dir)]\ntrain_imgs = train_dogs[:2000] + train_cats[:2000]\n\nrandom.shuffle(train_imgs)\n\ndel train_dogs\ndel train_cats\ngc.collect()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.image as mpimg\nfor ima in train_imgs[0:3]:\n    img = mpimg.imread(ima)\n    imgplot = plt.imshow(img)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#declare image dimmension to make all images the same size\nnrows = 150\nncolumns = 150\nchannels = 3 # for 3 color image 1 for grayscale\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_and_process_image(list_of_images):\n    \"\"\"\n    Returns two arrays\n    X is  array of resized images\n    y is array of labels\n    \"\"\"\n    X =[] #images\n    y=[] #labels\n    \n    for image in list_of_images:\n        X.append(cv2.resize(cv2.imread(image,cv2.IMREAD_COLOR), (nrows,ncolumns), interpolation=cv2.INTER_CUBIC))# read the images get the laabels\n        if 'dog.' in image:\n            y.append(1)\n        elif 'cat.' in image:\n            y.append(0)\n    return X,y\n                ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X,y = read_and_process_image(train_imgs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20,10))\ncolumns = 5\nfor i in range(columns):\n    plt.subplot(5/columns + 1,columns,i+1)\n    plt.imshow(X[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\ndel train_imgs\ngc.collect()\n\n#converrt list into numpy arrays\nX = np.array(X)\ny = np.array(y)\n\nsns.countplot(y)\nplt.title('Labels for cats and dogs')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX_train,X_test,y_train,y_test = train_test_split(X,y, test_size = 0.20,random_state=2)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del X\ndel y\ngc.collect()\n\nntrain = len(X_train)\nntest = len(X_test)\n\n#batch_size should be always be a factor of 2,4,8,16...\nbatch_size = 32\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications import InceptionResNetV2\nconv_base = InceptionResNetV2(weights='imagenet',include_top=False,input_shape=(150,150,3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"conv_base.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import layers,models,optimizers\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing.image import img_to_array,load_img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = models.Sequential()\nmodel.add(conv_base)\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},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(model.trainable_weights))\nconv_base.trainable=False\nprint(len(model.trainable_weights))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#use RMSprop with learning rate 0.0002\n#use binary cross entropy because its a binary classification\nmodel.compile(loss='binary_crossentropy',optimizer=optimizers.RMSprop(lr=2e-5),metrics=['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1./255, #scale the image between 0 and 1\n                                   rotation_range=40,\n                                   width_shift_range=0.2,\n                                   height_shift_range=0.2,\n                                   shear_range=0.2,\n                                   zoom_range=0.2,\n                                   horizontal_flip=True,)\nval_datagen=ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#create image generators\ntrain_generator = train_datagen.flow(X_train,y_train,batch_size=batch_size)\nval_generator = val_datagen.flow(X_test,y_test,batch_size=batch_size)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#train 20 epochs with 100 steps each epoch\nhistory = model.fit_generator(train_generator,\n                             steps_per_epoch=ntrain//batch_size,\n                             epochs=20,\n                             validation_data=val_generator,\n                             validation_steps=ntest//batch_size)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights('model_weights.h5')\nmodel.save('model_keras.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#plot train and test curve\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc) + 1)\n\n#train and validation accuracy\n\nplt.plot(epochs, acc, 'b', label='Training accuracy')\nplt.plot(epochs, val_acc, 'r', label='Validation accuracy')\nplt.title('Training and Validation accuracy')\nplt.legend()\nplt.figure()\n\n#Train and validatoin loss\nplt.plot(epochs, loss, 'b', label='Training loss')\nplt.plot(epochs,val_loss, 'r', label='Validation Loss')\nplt.title('Training and validation Accuracy')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test,y_test = read_and_process_image(test_imgs[0:10])\nx = np.array(X_test)\ntest_datagen = ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i=0\ntest_labels=[]\nplt.figure(figsize=(30,20))\nfor batch in test_datagen.flow(x,batch_size=1):\n    pred = model.predict(batch)\n    if pred>0.5:\n        test_labels.append('dog')\n    else:\n        test_labels.append('cat')\n    plt.subplot(5/columns + 1,columns,i + 1)\n    plt.title('This is a ' + test_labels[i])\n    imgplot = plt.imshow(batch[0])\n    i += 1\n    if i%10==0:\n        break\n    plt.show\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":1}