{"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)\nimport matplotlib.pyplot as plt\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\nimport os\nfrom PIL import Image\nprint(os.listdir(\"../input\"))\n\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pylab as plt\nimport seaborn as sns\n\nimport tensorflow as tf\ntf.enable_eager_execution()\n\nimport tensorflow_hub as hub\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = pd.read_csv('../input/sampleSubmission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = os.listdir(\"../input/train/train\")\ntrain_dir = \"../input/train/train\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image = Image.open(r\"../input/train/train/cat.11679.jpg\")\ndisplay(image)\nimage = np.array(image)\ndisplay(image.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categories = []\n\ntrain[0].split('.')[0]\n\nfor data in train:\n    category = data.split('.')[0]\n    if(category == 'cat'):\n        categories.append(0)\n    elif(category == 'dog'):\n        categories.append(1)\n\ntrain_df = pd.DataFrame({\n    'filename':train,\n    'category':categories\n})\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#plotting ham and spam data % in pie chart \ncount_Class=pd.value_counts(train_df.category, sort= True)\n\n# Data to plot\nlabels = 'dog', 'cat'\nsizes = [count_Class[0], count_Class[1]]\ncolors = ['blue', 'lightskyblue'] # 'lightcoral', 'lightskyblue'\nexplode = (0, 0)  # explode 1st slice\n \n# Plot\nplt.pie(sizes, explode=explode, labels=labels, colors=colors,\n        autopct='%1.1f%%', shadow=True, startangle=140)\nplt.axis('equal')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(tf.test.is_gpu_available())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 100\nIMG_SHAPE = 224\ntrain_generator = ImageDataGenerator(rescale=1./255)\ntest_generator = ImageDataGenerator(rescale = 1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()\ntrain_df.category=train_df.category.astype(str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data = train_generator.flow_from_dataframe(dataframe=train_df,directory=train_dir,x_col='filename',y_col='category',class_mode='binary',batch_size=BATCH_SIZE,\n                                            target_size=(IMG_SHAPE,IMG_SHAPE))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"#loading the state of art neural network \nURL = \"https://tfhub.dev/google/imagenet/inception_resnet_v2/classification/2\"\n\nIMAGE_RES = 224\n\nfeature_extractor =  hub.Module(URL)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Freezing so that the training modeifies only the final layer\nfeature_extractor.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(224, 224, 3)),\n    tf.keras.layers.MaxPooling2D(2, 2),\n\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512, activation='relu'),\n    tf.keras.layers.Dense(2, activation='softmax')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam',\n             loss='sparse_categorical_crossentropy',\n             metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nEPOCHS=10\nhistory = model.fit_generator(\n    train_data,\n    steps_per_epoch=20,\n    epochs=EPOCHS,\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history.history","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history.history['acc']\n\nloss = history.history['loss']\n\n\nepochs_range = range(EPOCHS)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training  Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.legend(loc='upper right')\nplt.title('Training  Loss')\nplt.savefig('./foo.png')\nplt.show()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}