{"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)\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 all files under the input directory\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\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":"from zipfile import ZipFile\nfrom PIL import Image\nimport random\nimport cv2\nimport glob\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom shutil import copyfile","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"file_name = \"/kaggle/input/dogs-vs-cats/train.zip\"\nfile_test = \"/kaggle/input/dogs-vs-cats/test1.zip\"\n\nwith ZipFile(file_name, 'r') as zip:  \n    # extracting all the files \n    print('Extracting all the files now...') \n    zip.extractall('/train')\n    print('Done!') \n    \nwith ZipFile(file_test,'r') as zip:\n    print('Extracting all files now...')\n    zip.extractall('/test1')\n    print('Done!')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(os.listdir('/train/train/')))\nprint(len(os.listdir('/test1/test1/')))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"main_dir = \"/kaggle/input/dogs-vs-cats\"\ntrain_dir = \"/train/train\"\ntest_dir = \"/test1/test1\"\npath_train = os.path.join(main_dir, train_dir)\npath_test = os.path.join(main_dir, test_dir)\npath_array = []\nlabel=[]\n\nfor file in os.listdir(path_train):\n    path_array.append(os.path.join(path_train,file))\n    if file.startswith(\"cat\"):\n        label.append('cat')\n    elif file.startswith(\"dog\"):\n        label.append('dog') \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(path_array[:5])\nprint(label[:5])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"d = {'path': path_array, 'label': label}\ndf_train = pd.DataFrame(data=d)\ndf_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(96,96,3)),\n                                    tf.keras.layers.MaxPooling2D(2,2),\n                                    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),\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.Flatten(),\n                                    tf.keras.layers.Dense(512, activation='relu'),\n                                    tf.keras.layers.Dense(2, activation='sigmoid')\n])\nmodel.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['acc'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_HT_WID = 96\ntrain_datagen = ImageDataGenerator(validation_split=0.1 ,rescale = 1.0/255.)\ntrain_generator = train_datagen.flow_from_dataframe(dataframe= df_train,x_col='path',y_col='label',subset=\"training\",batch_size=50,seed=42,shuffle=True, class_mode= 'categorical', target_size = (IMAGE_HT_WID,IMAGE_HT_WID))\n\nvalid_generator = train_datagen.flow_from_dataframe(dataframe= df_train,x_col='path',y_col='label',subset=\"validation\",batch_size=50,seed=42,shuffle=True, class_mode= 'categorical', target_size = (IMAGE_HT_WID,IMAGE_HT_WID))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCHS=5\nSTEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size\nSTEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size\nhistory = model.fit_generator(generator=train_generator,\n                    steps_per_epoch=STEP_SIZE_TRAIN,\n                    validation_data=valid_generator,\n                    validation_steps=STEP_SIZE_VALID,\n                    epochs=EPOCHS,\n                    verbose=1\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data=[]\nid=[]\ncounter=0\nfor file in os.listdir(path_test):\n    test_data.append(os.path.join(path_test,file))\n    \nprint(test_data[:5])\n\ndtest = {'path': test_data}\ndf_test = pd.DataFrame(data=dtest)\ndf_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale = 1./255.)\ntest_generator=test_datagen.flow_from_dataframe(\n                dataframe=df_test,\n                x_col=\"path\",\n                y_col=None,\n                batch_size=50,seed=42,\n                shuffle=False,\n                class_mode=None,\n                target_size=(96,96))\nSTEP_SIZE_TEST=test_generator.n//test_generator.batch_size\ntest_generator.reset()\npred=model.predict_generator(test_generator,\n                steps=STEP_SIZE_TEST,\n                verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nacc = history.history['acc']\nval_acc = history.history['val_acc']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend(loc=0)\nplt.figure()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_class_indices=np.argmax(pred,axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(predicted_class_indices)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_class_indices[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(predicted_class_indices)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(df_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"id = [*range(1,len(df_test)+1)]\ndataframe_output=pd.DataFrame({\"id\":id})\ndataframe_output[\"label\"]=predicted_class_indices\ndataframe_output.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataframe_output.head()","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":1}