{"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\nimport cv2\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\nfrom keras.preprocessing.image import img_to_array, load_img\nfrom sklearn.model_selection import train_test_split\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input/dogs-vs-cats-redux-kernels-edition'):\n    for filename in filenames:\n        print((filename))\n!unzip ../input/dogs-vs-cats-redux-kernels-edition/train.zip -d train\n!unzip ../input/dogs-vs-cats-redux-kernels-edition/test.zip -d test\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"folder = '/kaggle/working/train/train/'\n\ntrain_image=[folder+i for i in os.listdir(folder)]\ntrain_image_cat=[]\ntrain_image_dog=[]\nfor i in range(10000):\n    filename =folder+'cat.' + str(i)+ '.jpg'\n    train_image_cat.append(filename)\nfor i in range(10000):\n    filename=folder+'dog.' + str(i)+ '.jpg'\n    train_image_dog.append(filename)\ntrain_image=train_image_cat+train_image_dog \n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename =train_image_cat[i]\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = '/kaggle/working/train/train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = train_image_dog[i]\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dir = '/kaggle/working/test/test/'\n\n#test_image=[test_dir+i for i in os.listdir(test_dir)]\ntest_image=[]\nfor i in range(1,501):\n    filename =test_dir+ str(i)+'.jpg'\n    test_image.append(filename)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\ntest_dir = '/kaggle/working/test/test/'\n# plot first few images\nfor i in range(1,10):\n\t# define subplot\n\tpyplot.subplot(329 + 1 + i)\n\t# define filename\n\tfilename = test_image[i]\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_width=64\nimg_height=64","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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 = [] # labels\n    \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 list_of_images:\n        if 'dog' in i:\n            y.append(1)\n        elif 'cat' in i:\n            y.append(0)\n        #else:\n            #print('neither cat nor dog name present in images')\n            \n    return x, y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X, Y = prepare_data(train_image)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# First split the data in two sets, 80% for training, 20% for Val/Test)\nX_train, X_val, Y_train, Y_val = train_test_split(X,Y, test_size=0.2, random_state=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_train_samples = len(X_train)\nnb_validation_samples = len(X_val)\nbatch_size = 16","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras import optimizers\nclassifier = Sequential()\nclassifier.add(Conv2D(32,(3,3),input_shape=(64,64,3),activation = 'relu'))\nclassifier.add(MaxPooling2D(pool_size=(2,2),strides=2)) #if stride not given it equal to pool filter size\nclassifier.add(Conv2D(64,(3,3),activation = 'relu'))\nclassifier.add(MaxPooling2D(pool_size=(2,2),strides=2))\nclassifier.add(Conv2D(128,(3,3),activation = 'relu'))\nclassifier.add(MaxPooling2D(pool_size=(2,2),strides=2))\nclassifier.add(Flatten())\nclassifier.add(Dense(units=128,activation='relu'))\nclassifier.add(Dense(units=1,activation='sigmoid'))\nadam =optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\nclassifier.compile(optimizer=adam,loss='binary_crossentropy',metrics=['accuracy'])\n\nclassifier.summary()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(rescale=1./255,shear_range=0.1,zoom_range=0.1,horizontal_flip=True)\n\ntrain_generator = train_datagen.flow(np.array(X_train), Y_train, batch_size=batch_size)\n\nval_datagen = ImageDataGenerator(rescale=1. / 255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)\n\nvalidation_generator = val_datagen.flow(np.array(X_val), Y_val, batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = classifier.fit_generator(train_generator,steps_per_epoch=nb_train_samples // batch_size,epochs=30,validation_data=validation_generator,\n    validation_steps=nb_validation_samples // batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classifier.save_weights('classifier_wieghts.h5')\nclassifier.save('classifier_keras.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#import cv2\nX_test, Y_test = prepare_data(test_image) #Y_test in this case will be []","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1. / 255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import array_to_img\n#img1=array_to_img(X_test[0])\nfig=pyplot.figure(figsize=(15, 6))\ncolumns = 7\nrows = 3\nfor i in range(columns*rows):\n    fig.add_subplot(rows, columns, i+1)\n    img1=array_to_img(X_test[i])\n    img = X_test[i]\n    img=np.array(img).astype('float32')/255\n    img = np.expand_dims(img, axis=0) \n    prediction = classifier.predict(img,batch_size=None,steps=1) #gives all class prob.\n    if(prediction[:,:]>0.5):\n        value ='Dog :%1.2f'%(prediction[0,0])\n        pyplot.text(20, 58,value,color='red',fontsize=10,bbox=dict(facecolor='white',alpha=0.8))\n    else:\n        value ='Cat :%1.2f'%(1.0-prediction[0,0])\n        pyplot.text(20, 58,value,color='red',fontsize=10,bbox=dict(facecolor='white',alpha=0.8))\n    pyplot.imshow(img1)\n    #pyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_generator = test_datagen.flow(np.array(X_test), batch_size=batch_size)\n#prediction_probabilities = classifier.predict_generator(test_generator, verbose=0)\n# evaluate model\nx1=classifier.evaluate_generator(train_generator)\nx2=classifier.evaluate_generator(validation_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Training Accuracy  : %1.2f%%     Training loss  : %1.6f'%(x1[1]*100,x1[0]))\nprint('Validation Accuracy: %1.2f%%     Validation loss: %1.6f'%(x2[1]*100,x2[0]))","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}