{"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 20GB 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 random\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport tensorflow as tf\nfrom tensorflow import keras\nimport zipfile\nimport shutil","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def extract_files(source, target):\n    unzip_source = zipfile.ZipFile(source, 'r')\n    unzip_source.extractall(target)\n    unzip_source.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('/kaggle/input/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"extract_files('/kaggle/input/dogs-vs-cats/test1.zip', '/kaggle/working/')\nextract_files('/kaggle/input/dogs-vs-cats/train.zip', '/kaggle/working/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_dir = ('/kaggle/working/')\nbase_dir","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('/kaggle/working/train')[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(os.listdir('/kaggle/working/train')))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.makedirs('/kaggle/working/training/dogs')\n\nos.makedirs('/kaggle/working/training/cats')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"target_path = '/kaggle/working/training/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(target_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def copy_file(file_path, file_name, target):\n    source_path = os.path.join(file_path, file_name)\n    final_path = os.path.join(target_path, target)\n    shutil.copy(source_path, final_path)\n\n\ndef separate_files(file_path):\n    for img in os.listdir(file_path):\n        \n        if img.split('.')[0] == 'cat':\n            copy_file(file_path, img, os.path.join(target_path, 'cats'))\n        else:\n            copy_file(file_path, img, os.path.join(target_path, 'dogs'))\n    \n    \n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"separate_files(os.path.join(base_dir, 'train'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(os.path.join(base_dir,'training','cats'))[:20]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(os.listdir(os.path.join(base_dir,'training','cats'))))\nprint(len(os.listdir(os.path.join(base_dir,'training','dogs'))))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cat_folder = os.path.join(os.path.join(base_dir,'training','cats'))\ndog_folder = os.path.join(os.path.join(base_dir,'training','dogs'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_dir = os.path.join(base_dir, 'training')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(10,10))\n\nfor i in range(15):\n    sub_dir_name = np.random.choice(os.listdir(data_dir))\n    sub_dir = os.path.join(data_dir, sub_dir_name)\n    img_file = os.path.join(sub_dir, np.random.choice([x for x in os.listdir(sub_dir)] ))\n    \n    plt.subplot(5,5,i+1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    img = plt.imread(img_file)\n    plt.imshow(img)\n    plt.xlabel(f'dir: {sub_dir_name}')\n    \nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_gen = ImageDataGenerator(rescale = 1.0/255.0, \n                              shear_range= 0.2,\n                              zoom_range= 0.3,\n                              width_shift_range = 0.2,\n                              height_shift_range = 0.2,\n                              horizontal_flip= True,\n                              vertical_flip= True,\n                              rotation_range= 45,\n                              validation_split= 0.2,\n                              )\n\nvalid_gen = ImageDataGenerator(rescale = 1.0/255.0,\n                              shear_range= 0.2,\n                              zoom_range= 0.3,\n                              horizontal_flip= True,\n                              vertical_flip= True,\n                              rotation_range= 45,\n                              validation_split= 0.2,\n                              )\n                               \ntrain_ds = train_gen.flow_from_directory(data_dir,\n                                         target_size= (150,150),\n                                         shuffle= True,\n                                         batch_size = 256,\n                                         seed= 7,\n                                         subset= 'training',\n                                         class_mode=\"binary\"\n                                         )    \n\n\nvalid_ds = valid_gen.flow_from_directory(data_dir,\n                                         target_size= (150,150),\n                                         shuffle= True,\n                                         batch_size = 256,\n                                         seed= 7,\n                                         subset= 'validation',\n                                         class_mode= \"binary\"\n                                         )   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from keras.applications.inception_resnet_v2 import InceptionResNetV2\n# from keras.applications.inception_resnet_v2 import preprocess_input\n# from keras.applications.inception_resnet_v2 import decode_predictions\n# from sklearn.metrics import accuracy_score\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.keras.backend.clear_session()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model = tf.keras.applications.MobileNetV2(input_shape = (160,160,3), \n                                               weights= 'imagenet', \n                                               include_top = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"global_avg_layer = tf.keras.layers.GlobalAveragePooling2D()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential([base_model,\n                            tf.keras.layers.Flatten(),\n                            tf.keras.layers.Dense(512, activation = 'relu'),\n                            tf.keras.layers.Dropout(0.5), \n                            tf.keras.layers.Dense(1, activation = 'sigmoid')])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer= tf.keras.optimizers.Adam(learning_rate= 0.01), \n             loss = tf.keras.losses.BinaryCrossentropy(from_logits= False),\n             metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"early_stop = tf.keras.callbacks.EarlyStopping(patience = 10)\nreduce_on_plateau = tf.keras.callbacks.ReduceLROnPlateau(patience = 5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(train_ds, epochs=200, validation_data= valid_ds, callbacks= [early_stop, reduce_on_plateau])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# detect and init the TPU\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)\n\n# instantiating the model in the strategy scope creates the model on the TPU\n# with tpu_strategy.scope():\n#     model = tf.keras.Sequential( … ) # define your model normally\n#     model.compile( … )\n\n# # train model normally\n# model.fit(training_dataset, epochs=EPOCHS, steps_per_epoch)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nmodel1 = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Dropout(0.25),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512, activation='relu'),\n    tf.keras.layers.Dropout(0.25),\n    tf.keras.layers.Dense(1, activation='sigmoid')  \n])\n\nmodel1.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model1.compile(tf.keras.optimizers.Adam(learning_rate= 0.001),\n              loss='binary_crossentropy',\n              metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model1.fit_generator(\n        train_ds,\n        epochs=50,\n        validation_data= valid_ds,\n        callbacks= [early_stop, reduce_on_plateau])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\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 20GB 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\n\nimport random\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport tensorflow as tf\nfrom tensorflow import keras\nimport zipfile\nimport shutil\n\ndef extract_files(source, target):\n    unzip_source = zipfile.ZipFile(source, 'r')\n    unzip_source.extractall(target)\n    unzip_source.close()\n\nos.listdir('/kaggle/input/')\n\nextract_files('/kaggle/input/dogs-vs-cats/test1.zip', '/kaggle/working/')\nextract_files('/kaggle/input/dogs-vs-cats/train.zip', '/kaggle/working/')\n\nbase_dir = ('/kaggle/working/')\nbase_dir\n\nos.listdir('/kaggle/working/train')[:10]\n\nprint(len(os.listdir('/kaggle/working/train')))\n\nos.makedirs('/kaggle/working/training/dogs')\n\nos.makedirs('/kaggle/working/training/cats')\n\ntarget_path = '/kaggle/working/training/'\n\nos.listdir(target_path)\n\ndef copy_file(file_path, file_name, target):\n    source_path = os.path.join(file_path, file_name)\n    final_path = os.path.join(target_path, target)\n    shutil.copy(source_path, final_path)\n\n\ndef separate_files(file_path):\n    for img in os.listdir(file_path):\n        \n        if img.split('.')[0] == 'cat':\n            copy_file(file_path, img, os.path.join(target_path, 'cats'))\n        else:\n            copy_file(file_path, img, os.path.join(target_path, 'dogs'))\n    \n    \n        \n\nseparate_files(os.path.join(base_dir, 'train'))\n\nos.listdir(os.path.join(base_dir,'training','cats'))[:20]\n\nprint(len(os.listdir(os.path.join(base_dir,'training','cats'))))\nprint(len(os.listdir(os.path.join(base_dir,'training','dogs'))))\n\ncat_folder = os.path.join(os.path.join(base_dir,'training','cats'))\ndog_folder = os.path.join(os.path.join(base_dir,'training','dogs'))\n\ndata_dir = os.path.join(base_dir, 'training')\n\nplt.figure(figsize=(10,10))\n\nfor i in range(15):\n    sub_dir_name = np.random.choice(os.listdir(data_dir))\n    sub_dir = os.path.join(data_dir, sub_dir_name)\n    img_file = os.path.join(sub_dir, np.random.choice([x for x in os.listdir(sub_dir)] ))\n    \n    plt.subplot(5,5,i+1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    img = plt.imread(img_file)\n    plt.imshow(img)\n    plt.xlabel(f'dir: {sub_dir_name}')\n    \nplt.show()\n\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_gen = ImageDataGenerator(rescale = 1.0/255.0, \n                              shear_range= 0.2,\n                              zoom_range= 0.3,\n                              width_shift_range = 0.2,\n                              height_shift_range = 0.2,\n                              horizontal_flip= True,\n                              vertical_flip= True,\n                              rotation_range= 45,\n                              validation_split= 0.2,\n                              )\n\nvalid_gen = ImageDataGenerator(rescale = 1.0/255.0,\n                              shear_range= 0.2,\n                              zoom_range= 0.3,\n                              horizontal_flip= True,\n                              vertical_flip= True,\n                              rotation_range= 45,\n                              validation_split= 0.2,\n                              )\n                               \ntrain_ds = train_gen.flow_from_directory(data_dir,\n                                         target_size= (160,160),\n                                         shuffle= True,\n                                         batch_size = 128,\n                                         seed= 7,\n                                         subset= 'training'\n                                         )    \n\n\nvalid_ds = valid_gen.flow_from_directory(data_dir,\n                                         target_size= (160,160),\n                                         shuffle= True,\n                                         batch_size = 128,\n                                         seed= 7,\n                                         subset= 'validation'\n                                         )   \n\n# from keras.applications.inception_resnet_v2 import InceptionResNetV2\n# from keras.applications.inception_resnet_v2 import preprocess_input\n# from keras.applications.inception_resnet_v2 import decode_predictions\n# from sklearn.metrics import accuracy_score\n\n\ntf.keras.backend.clear_session()\n\n\nbase_model = tf.keras.applications.MobileNetV2(input_shape = (160,160,3), \n                                               weights= 'imagenet', \n                                               include_top = False)\n\nbase_model.trainable = False\n\nbase_model.summary()\n\nglobal_avg_layer = tf.keras.layers.GlobalAveragePooling2D()\n\nmodel = tf.keras.Sequential([base_model, \n                            tf.keras.layers.Flatten(),\n                            tf.keras.layers.Dense(512, activation = 'relu'),\n                            tf.keras.layers.Dropout(0.5), \n                            tf.keras.layers.Dense(1, activation = 'sigmoid')])\n\nmodel.summary()\n\nmodel.compile(optimizer= tf.keras.optimizers.Adam(learning_rate= 0.01), \n             loss = tf.keras.losses.BinaryCrossentropy(from_logits= False),\n             metrics = ['accuracy'])\n\nearly_stop = tf.keras.callbacks.EarlyStopping(patience = 10)\nreduce_on_plateau = tf.keras.callbacks.ReduceLROnPlateau(patience = 5)\n\nhistory = model.fit(train_ds, epochs=200, validation_data= valid_ds, callbacks= [early_stop, reduce_on_plateau])","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}