{"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_minor":4,"nbformat":4,"cells":[{"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-03-16T06:24:44.420779Z","iopub.execute_input":"2022-03-16T06:24:44.421188Z","iopub.status.idle":"2022-03-16T06:24:44.450417Z","shell.execute_reply.started":"2022-03-16T06:24:44.42108Z","shell.execute_reply":"2022-03-16T06:24:44.449669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\n\nTrain_path  = '/kaggle/input/dogs-vs-cats/test1.zip'\nTest_path = '/kaggle/input/dogs-vs-cats/train.zip'\n\nFILES = \"/kaggle/files/unzipped/\"\n\nwith zipfile.ZipFile(Train_path, 'r') as zipp:\n    zipp.extractall(FILES)\n    \nwith zipfile.ZipFile(Test_path, 'r') as zipp:\n    zipp.extractall(FILES)\n    \nos.listdir('/kaggle/files/unzipped/')","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:24:44.452146Z","iopub.execute_input":"2022-03-16T06:24:44.452472Z","iopub.status.idle":"2022-03-16T06:25:01.13079Z","shell.execute_reply.started":"2022-03-16T06:24:44.452438Z","shell.execute_reply":"2022-03-16T06:25:01.130126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:01.131891Z","iopub.execute_input":"2022-03-16T06:25:01.132571Z","iopub.status.idle":"2022-03-16T06:25:05.242537Z","shell.execute_reply.started":"2022-03-16T06:25:01.132531Z","shell.execute_reply":"2022-03-16T06:25:05.241807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\ntraining_images_file = os.listdir('/kaggle/files/unzipped/train')\ntest_image_files=os.listdir(\"/kaggle/files/unzipped/test1\")","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:05.243649Z","iopub.execute_input":"2022-03-16T06:25:05.243897Z","iopub.status.idle":"2022-03-16T06:25:05.270354Z","shell.execute_reply.started":"2022-03-16T06:25:05.243852Z","shell.execute_reply":"2022-03-16T06:25:05.269683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes=[]\nfor f in training_images_file:\n    class_name = f.split('.')[0]\n    classes.append(class_name)\n    \ntrain_df = pd.DataFrame({\n    'filename': training_images_file,\n    'class': classes\n})","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:05.272739Z","iopub.execute_input":"2022-03-16T06:25:05.273056Z","iopub.status.idle":"2022-03-16T06:25:05.307178Z","shell.execute_reply.started":"2022-03-16T06:25:05.273021Z","shell.execute_reply":"2022-03-16T06:25:05.306558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df=train_df.reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:05.308268Z","iopub.execute_input":"2022-03-16T06:25:05.308517Z","iopub.status.idle":"2022-03-16T06:25:05.313015Z","shell.execute_reply.started":"2022-03-16T06:25:05.308483Z","shell.execute_reply":"2022-03-16T06:25:05.312283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:05.314397Z","iopub.execute_input":"2022-03-16T06:25:05.314958Z","iopub.status.idle":"2022-03-16T06:25:05.335749Z","shell.execute_reply.started":"2022-03-16T06:25:05.314925Z","shell.execute_reply":"2022-03-16T06:25:05.335099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_df, validate_df = train_test_split(train_df, test_size=0.20)","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:05.336841Z","iopub.execute_input":"2022-03-16T06:25:05.337075Z","iopub.status.idle":"2022-03-16T06:25:06.035545Z","shell.execute_reply.started":"2022-03-16T06:25:05.337045Z","shell.execute_reply":"2022-03-16T06:25:06.034813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\ntrain_datagen=ImageDataGenerator(\n            rescale=1/255.,\n            rotation_range=45,\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            '/kaggle/files/unzipped/train/',\n            x_col='filename',\n            y_col='class',\n            target_size=(299,299),\n            batch_size=128,\n            class_mode='binary'\n\n)\n\n\nvalidation_datagen=ImageDataGenerator(\n            rescale=1/255\n)\n\nvalidation_generator=validation_datagen.flow_from_dataframe(\n            validate_df,\n            '/kaggle/files/unzipped/train/',\n            x_col='filename',\n            y_col='class',\n            target_size=(299,299),\n            batch_size=128,\n            class_mode='binary'\n\n)","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:06.036932Z","iopub.execute_input":"2022-03-16T06:25:06.037204Z","iopub.status.idle":"2022-03-16T06:25:07.142908Z","shell.execute_reply.started":"2022-03-16T06:25:06.037169Z","shell.execute_reply":"2022-03-16T06:25:07.142173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications.inception_v3 import InceptionV3\npre_trained_model = InceptionV3(input_shape = (299, 299, 3),\n                                include_top = False,\n                                weights = 'imagenet')\n\nfor layer in pre_trained_model.layers:\n    layer.trainable=True\n    \npre_trained_model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:07.144031Z","iopub.execute_input":"2022-03-16T06:25:07.144601Z","iopub.status.idle":"2022-03-16T06:25:14.745659Z","shell.execute_reply.started":"2022-03-16T06:25:07.14456Z","shell.execute_reply":"2022-03-16T06:25:14.729266Z"},"scrolled":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow import keras\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.optimizers import RMSprop\n\n\nlast_layer = pre_trained_model.get_layer('mixed10')\n\nlast_output=last_layer.output\n\ndef create_model(last_output):\n    x=keras.layers.Flatten()(last_output)\n    x=keras.layers.Dense(128, activation='relu')(x)\n    x=keras.layers.Dropout(0.4)(x)\n    x=keras.layers.Dense(64, activation='relu')(x)\n    x=keras.layers.Dense(1, activation='sigmoid')(x)\n\n    model = Model(pre_trained_model.input, x)\n\n    model.compile(optimizer = RMSprop(learning_rate=0.001),\n                  loss = 'binary_crossentropy',\n                  metrics = ['acc'])\n    return model\n\n\n\nmodel=create_model(last_output)\n    \n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:14.748005Z","iopub.execute_input":"2022-03-16T06:25:14.748269Z","iopub.status.idle":"2022-03-16T06:25:14.990757Z","shell.execute_reply.started":"2022-03-16T06:25:14.748218Z","shell.execute_reply":"2022-03-16T06:25:14.989965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\n\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',\n                                            patience=2,\n                                            verbose=1,\n                                            factor=0.5,\n                                            min_delt=0.001,\n                                            min_lr=0.00001)\n\nearly_stopping = EarlyStopping(\n    monitor = \"val_accuracy\",\n    patience = 50,\n    verbose = 1,\n    mode = \"max\",\n)","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:14.992024Z","iopub.execute_input":"2022-03-16T06:25:14.992548Z","iopub.status.idle":"2022-03-16T06:25:15.49091Z","shell.execute_reply.started":"2022-03-16T06:25:14.99251Z","shell.execute_reply":"2022-03-16T06:25:15.490068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ntf.keras.backend.clear_session()\n\nhistory=model.fit(\n    train_generator,\n    epochs=10,\n    validation_data=validation_generator,\n    callbacks=[learning_rate_reduction, early_stopping]\n)","metadata":{"execution":{"iopub.status.busy":"2022-03-16T06:25:15.492081Z","iopub.execute_input":"2022-03-16T06:25:15.492936Z","iopub.status.idle":"2022-03-16T07:46:07.002572Z","shell.execute_reply.started":"2022-03-16T06:25:15.492901Z","shell.execute_reply":"2022-03-16T07:46:07.001865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import load_img, img_to_array\nimport random\n\ntest_images=[]\ntest_image_files=random.sample(test_image_files, 500)\nfor test_image in test_image_files:\n    test_images.append(img_to_array(load_img('/kaggle/files/unzipped/test1/'+test_image, target_size=(299,299)))/255.)","metadata":{"execution":{"iopub.status.busy":"2022-03-16T07:46:07.005811Z","iopub.execute_input":"2022-03-16T07:46:07.006023Z","iopub.status.idle":"2022-03-16T07:46:08.492218Z","shell.execute_reply.started":"2022-03-16T07:46:07.005998Z","shell.execute_reply":"2022-03-16T07:46:08.491482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_images=np.array(test_images)","metadata":{"execution":{"iopub.status.busy":"2022-03-16T07:46:08.493526Z","iopub.execute_input":"2022-03-16T07:46:08.493799Z","iopub.status.idle":"2022-03-16T07:46:08.677974Z","shell.execute_reply.started":"2022-03-16T07:46:08.493763Z","shell.execute_reply":"2022-03-16T07:46:08.677267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions=model.predict(test_images)","metadata":{"execution":{"iopub.status.busy":"2022-03-16T07:46:08.679407Z","iopub.execute_input":"2022-03-16T07:46:08.679673Z","iopub.status.idle":"2022-03-16T07:46:12.249428Z","shell.execute_reply.started":"2022-03-16T07:46:08.67964Z","shell.execute_reply":"2022-03-16T07:46:12.248665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot as plt\n\ni=random.randint(0, len(predictions))\nprint(predictions[i])\nif predictions[i] >0.5:\n    print('Its a Dog')\nelse:\n    print('Its a Cat')\n          \n\nplt.imshow(test_images[i], interpolation='nearest')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-03-16T07:46:12.251126Z","iopub.execute_input":"2022-03-16T07:46:12.251402Z","iopub.status.idle":"2022-03-16T07:46:12.469574Z","shell.execute_reply.started":"2022-03-16T07:46:12.251366Z","shell.execute_reply":"2022-03-16T07:46:12.466817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}