{"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\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 read-only \"../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# 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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os\nimport tensorflow as tf\n#print(os.listdir(\"../input\"))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\nwith zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"../input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":" # detect and init the TPU\nimport tensorflow as tf\ntpu = tf.distribute.cluster_resolver.TPUClusterResolver()\ntf.config.experimental_connect_to_cluster(tpu)\ntf.tpu.experimental.initialize_tpu_system(tpu)\n    \n    # instantiate a distribution strategy\ntpu_strategy = tf.distribute.experimental.TPUStrategy(tpu)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = os.listdir(\"../working/train\")\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\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":"df.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['category']=df['category'].replace({1:'dog',0:'cat'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['category'].value_counts().plot.bar()\n#1-dog\n#2-cat","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#viewing a random image\nsample=random.choice(filenames)\nimage=load_img(\"../working/train/\"+sample)\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Building a CNN Model using keras","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nIMAGE_WIDTH=120\nIMAGE_HEIGHT=120\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS=3\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\n\n#tpu_strategy = tf.distribute.experimental.TPUStrategy(tpu)\n#with tpu_strategy.scope():\nmodel=Sequential()\nmodel.add(Conv2D(32, (3, 3), \n                     activation='relu',\n                     input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(60, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\n    \nmodel.add(Conv2D(100,(3,3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n    \nmodel.add(Flatten())\nmodel.add(Dense(300,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n    \n    \nmodel.add(Dense(2, activation='softmax'))\nmodel.compile(loss=\"categorical_crossentropy\",optimizer='adam',metrics=['accuracy'])\n    \n        \n     \n\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#using earlystooping to prevent overfitting and learning rate reduction \nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\nearlystop=EarlyStopping(patience=10)\nlearning_rate_reduction=ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.000010)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callbacks=[earlystop,learning_rate_reduction]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#preproccesing data for ImageDataGenerator\ntrain_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df = validate_df.reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validate_df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_total=train_df.shape[0]\nvalidate_total=train_df.shape[0]\nbatch_size=32\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rotation_range=15,\n    rescale=1./255,\n    shear_range=0.1,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"../working/train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidate_df['category']=validate_df['category'].replace({1:'dog',0:'cat'})\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"../working/train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"example_df = train_df.sample(n=1).reset_index(drop=True)\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df, \n    \"../working/train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12, 12))\nfor i in range(0, 15):\n    plt.subplot(5, 3, i+1)\n    for X_batch, Y_batch in example_generator:\n        image = X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#fitting our model\nepochs=35\nhistory=model.fit_generator(\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=validate_total//batch_size,\n    steps_per_epoch=train_total//batch_size,\n    callbacks=callbacks\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights('model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#plotting out the training\n\nfig,(ax1,ax2)=plt.subplots(2,1,figsize=(12,12))\n\nax1.plot(history.history['loss'],color='b',label='training loss')\nax1.plot(history.history['val_loss'],color='r',label='validation loss')\nax1.set_xticks(np.arange(1,epochs,1))\n\n\nax2.plot(history.history['accuracy'],color='b',label='training accuracy')\nax2.plot(history.history['val_accuracy'],color='r',label='validation accuracy')\nax2.set_xticks(np.arange(1,epochs,1))\n\n\nlegend=plt.legend(loc='best',shadow=True)\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#preprocessing training data\ntest_filenames = os.listdir(\"../working/test1\")\n#print(test_filenames)\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]\n\n#creating testing generator\ntest_gen=ImageDataGenerator(rescale=1./255)\ntest_generator=test_gen.flow_from_dataframe(\n    test_df,\n\"../working/test1/\",\nx_col=\"filename\",\ny_col=None,\nclass_mode=None,\ntarget_size=IMAGE_SIZE,\nbatch_size=batch_size,\nshuffle=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"prediction=model.predict_generator(test_generator,steps=np.ceil(nb_samples/batch_size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category']=np.argmax(prediction,axis=-1)\nlabel_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)\n#test_df['category']=test_df['category'].replace({'dog':1,'cat':0})\ntest_df['category'].value_counts().plot.bar()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n#test_df['category']=test_df['category'].replace({0:'cat',1:'dog'})\nsample_test=test_df.head(18)\nsample_test.head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_test.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#sampling first 30 images\n\nsample_test=test_df.head(36)\nsample_test.head()\nplt.figure(figsize=(18,36))\nfor i,r in sample_test.iterrows():\n    filename=r['filename']\n    category=r['category']\n    img=load_img(\"../working/test1/\"+filename,target_size=IMAGE_SIZE)\n    plt.subplot(6,6,i+1)\n    plt.imshow(img)\n    plt.xlabel(filename+\" \"+format(category))\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#sampling last 30 images\nsample_test=test_df.tail(36)\nsample_test.head()\nplt.figure(figsize=(12,24))\nfor i,r in sample_test.iterrows():\n    filename=r['filename']\n    category=r['category']\n    img=load_img(\"../working/test1/\"+filename,target_size=IMAGE_SIZE)\n    plt.subplot(6,6,12500-i)\n    plt.imshow(img)\n    plt.xlabel(filename+\" \"+format(category))\nplt.tight_layout()\nplt.show()","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":4}