{"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 matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.layers import  MaxPool2D, Conv2D, BatchNormalization, Dropout, Flatten, Dense\nimport os\nimport cv2\nimport zipfile\nfrom shutil import copyfile, move\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile('../input/dogs-vs-cats-redux-kernels-edition/train.zip', 'r') as zip_ref:\n    zip_ref.extractall()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.mkdir('training')\nos.mkdir('training/dogs')\nos.mkdir('training/cats')\nos.mkdir('validation')\nos.mkdir('validation/dogs')\nos.mkdir('validation/cats')\nos.mkdir('testing')\nos.mkdir('testing/unknown')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for item in tqdm(os.listdir('train')):\n    if item[-4:] == '.jpg':\n        img = cv2.imread('train/'+item)\n        img = cv2.resize(img, (100,100))\n        if item[:3] == 'cat':\n            cv2.imwrite('training/cats/'+item, img)\n        if item[:3] == 'dog':\n            cv2.imwrite('training/dogs/'+item, img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(os.listdir('training/dogs')))\nprint(len(os.listdir('training/cats')))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from shutil import move\n \nfor i in tqdm(range(2500)):\n    random_cat =  os.listdir('training/cats')[np.random.randint(9900)]\n    random_cat_path = 'training/cats/' + random_cat\n    random_dog =os.listdir('training/dogs')[np.random.randint(9990)]\n    random_dog_path =  'training/dogs/' + random_dog\n    \n    \n    move(random_cat_path, 'validation/cats/'+ random_cat)\n    move(random_dog_path, 'validation/dogs/'+ random_dog)\n    \n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(os.listdir('training/cats')))\nimg = cv2.imread('training/cats/' + os.listdir('training/cats')[54])\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n                                                                  \n\ntraining_data = train_gen.flow_from_directory('training/', target_size = (100,100),\n                                              batch_size = 64, class_mode = 'binary')\n\nvalidation_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n\nvalidation_data = train_gen.flow_from_directory('validation', target_size = (100,100),\n                                              batch_size = 32, class_mode = 'binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential([Conv2D(32, (3,3), activation = 'relu', input_shape = (100,100,3)),\n                                    MaxPool2D(),\n                                    Conv2D(32, (3,3), activation = 'relu'),\n                                    MaxPool2D(),\n                                    Conv2D(64, (3,3), activation = 'relu'),\n                                    MaxPool2D(),\n                                    Flatten(),\n                                    Dense(128, activation = 'relu'),\n                                    Dense(64,activation = 'relu'),\n                                    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(loss = 'binary_crossentropy', optimizer='adam', metrics = ['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(training_data, epochs = 4, validation_data=validation_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.legend(['loss', 'val_loss'])\nplt.show()\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.legend(['acc', 'val_acc'])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile('../input/dogs-vs-cats-redux-kernels-edition/test.zip', 'r') as zip_ref:\n    zip_ref.extractall()\nfor item in tqdm(os.listdir('test')):\n    if item[-4:] == '.jpg':\n        img = cv2.imread('test/'+item)\n        img = cv2.resize(img, (100,100))\n        cv2.imwrite('testing/unknown/'+item, img)\n        \ntest_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n                                                                  \n\ntesting_data = train_gen.flow_from_directory('testing/', target_size = (100,100))\n\nsubmission = model.predict_proba(training_data, verbose=1)\ntest_id = range(1,12501)\n#predictions_df = pd.DataFrame({'id': test_id, 'label': submission[:,0]})\n\n#predictions_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vggmodel = tf.keras.applications.vgg16.VGG16(include_top=False,input_shape = (100,100,3))\nvggmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for layers in vggmodel.layers:\n    layers.trainable =False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#vggmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential([vggmodel,\n                            Flatten(),\n                            Dense(64, activation = 'relu'),\n                            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":"model.compile( loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\nhistory = model.fit_generator(training_data, epochs = 4, validation_data= validation_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.legend(['loss', 'val_loss'])\nplt.show()\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.legend(['accuracy', 'val_accuracy'])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = model.predict_proba(testing_data, verbose=1)\ntest_id = range(1,12501)\npredictions_df = pd.DataFrame({'id': test_id, 'label': submission[:,0]})\n\npredictions_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inception_net = tf.keras.applications.inception_resnet_v2.InceptionResNetV2(include_top=False,input_shape = (100,100,3))\ninception_net.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential([inception_net,\n                            Flatten(),\n                            Dense(64, activation = 'relu'),\n                            Dense(1, activation = 'sigmoid')])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile( loss = 'binary_crossentropy', optimizer = tf.keras.optimizers.Adam(), metrics = ['accuracy'])\nhistory = model.fit_generator(training_data, epochs = 2, validation_data= validation_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.legend(['loss', 'val_loss'])\nplt.show()\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.legend(['accuracy', 'val_accuracy'])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = model.predict_proba(testing_data, verbose=1)\ntest_id = range(1,12501)\npredictions_df = pd.DataFrame({'id': test_id, 'label': submission[:,0]})\n\npredictions_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions_df['label'] = np.uint8(np.round(predictions_df['label']))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions_df","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}