{"cells":[{"metadata":{},"cell_type":"markdown","source":"#Image Generator"},{"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 the files in the input directory\n\nimport os\nprint(len(os.listdir(\"../input/train\")))\n\n# Any results you write to the current directory are saved as output.","execution_count":1,"outputs":[{"output_type":"stream","text":"25001\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.mkdir(\"modifiedtrain\")\nos.mkdir(\"modifiedtrain/cat\")\nos.mkdir(\"modifiedtrain/dog\")","execution_count":2,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(\"modifiedtrain\")","execution_count":3,"outputs":[{"output_type":"execute_result","execution_count":3,"data":{"text/plain":"['dog', 'cat']"},"metadata":{}}]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"from shutil import copyfile\nfor file in os.listdir(\"../input/train\"):\n    name=file.split('.')[0]\n    filename=\"../input/train/\"+file\n    if name=='cat':\n        copyfile(filename,\"modifiedtrain/cat/\"+file)\n    elif name=='dog':\n        copyfile(filename,\"modifiedtrain/dog/\"+file)\n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(\"modifiedtrain/dog/\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%pylab inline\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimage = Image.open('modifiedtrain/dog/dog.411.jpg')\nplt.imshow(image)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen=ImageDataGenerator(rescale=1./255)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator=train_datagen.flow_from_directory(\"modifiedtrain/\",batch_size=20,target_size=(150,150),\n                                                  class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(16,(3,3),activation='relu',input_shape=(150,150,3)),\n    tf.keras.layers.MaxPool2D(2,2),\n    tf.keras.layers.Conv2D(32,(3,3),activation='relu'),\n    tf.keras.layers.MaxPool2D(2,2),\n    tf.keras.layers.Conv2D(64,(3,3),activation='relu'),\n    tf.keras.layers.MaxPool2D(2,2),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512,activation='relu'),\n    tf.keras.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":"from tensorflow.keras.optimizers import RMSprop\n\nmodel.compile(loss='binary_crossentropy',optimizer=RMSprop(lr=0.001),metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit_generator(train_generator,steps_per_epoch=100,epochs=15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n      rescale=1./255,\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,\n      fill_mode='nearest')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator=train_datagen.flow_from_directory(\"modifiedtrain/\",batch_size=20,target_size=(150,150),\n                                                  class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit_generator(train_generator,steps_per_epoch=100,epochs=5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\n\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Model\n!wget --no-check-certificate \\\n    https://storage.googleapis.com/mledu-datasets/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5 \\\n    -O /tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5\n  \nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\n\nlocal_weights_file = '/tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'\n\npre_trained_model = InceptionV3(input_shape = (256, 256, 3), \n                                include_top = False, \n                                weights = None)\n\npre_trained_model.load_weights(local_weights_file)\n\nfor layer in pre_trained_model.layers:\n  layer.trainable = False\n  \n# pre_trained_model.summary()\n\nlast_layer = pre_trained_model.get_layer('mixed7')\nprint('last layer output shape: ', last_layer.output_shape)\nlast_output = last_layer.output","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.optimizers import RMSprop\n\n# Flatten the output layer to 1 dimension\nx = layers.Flatten()(last_output)\n# Add a fully connected layer with 1,024 hidden units and ReLU activation\nx = layers.Dense(1024, activation='relu')(x)\n# Add a dropout rate of 0.2\nx = layers.Dropout(0.2)(x)                  \n# Add a final sigmoid layer for classification\nx = layers.Dense  (1, activation='sigmoid')(x)           \n\nmodel = Model( pre_trained_model.input, x) \n\nmodel.compile(optimizer = RMSprop(lr=0.0001), \n              loss = 'binary_crossentropy', \n              metrics = ['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(\n      rescale=1./255,\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,\n      fill_mode='nearest')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator=train_datagen.flow_from_directory(\"modifiedtrain/\",batch_size=20,target_size=(256,256),\n                                                  class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit_generator(train_generator,steps_per_epoch=100,epochs=5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nacc = history.history['acc']\nloss = history.history['loss']\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.legend(loc=0)\nplt.figure()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(epochs, loss, 'b', label='Training loss')\nplt.legend(loc=0)\nplt.figure()","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}