{"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 zipfile\nimport random\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\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\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\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":"2021-12-03T11:04:44.556010Z","iopub.execute_input":"2021-12-03T11:04:44.556880Z","iopub.status.idle":"2021-12-03T11:04:44.570501Z","shell.execute_reply.started":"2021-12-03T11:04:44.556826Z","shell.execute_reply":"2021-12-03T11:04:44.569562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\", 'r') as zipp:\n    zipp.extractall(\"/kaggle/files/\")\n    \nwith zipfile.ZipFile(\"../input/dogs-vs-cats/test1.zip\", 'r') as zipp:\n    zipp.extractall(\"/kaggle/files/\")\n    \nos.listdir(\"/kaggle/files/\")","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:04:44.572163Z","iopub.execute_input":"2021-12-03T11:04:44.572776Z","iopub.status.idle":"2021-12-03T11:05:03.663120Z","shell.execute_reply.started":"2021-12-03T11:04:44.572732Z","shell.execute_reply":"2021-12-03T11:05:03.662342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_img = os.listdir(\"/kaggle/files/train/\")\ntest_img = os.listdir(\"/kaggle/files/test1/\")\n\n#print(train_image[0].split(\".\"))\nfiles = []\nclasses = []\nfor file in train_img:\n    files.append(file)\n    if file.startswith(\"dog\"):\n        classes.append(\"1\")\n    else:\n        classes.append(\"0\")\nprint(classes[:10])\n\nd_train = pd.DataFrame({\n    \"file\":train_img,\n    \"class\":classes\n})\nd_train = d_train.reset_index(drop=True)\nprint(d_train)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:03.664336Z","iopub.execute_input":"2021-12-03T11:05:03.664659Z","iopub.status.idle":"2021-12-03T11:05:03.710487Z","shell.execute_reply.started":"2021-12-03T11:05:03.664618Z","shell.execute_reply":"2021-12-03T11:05:03.709569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#print(test_image)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:03.712855Z","iopub.execute_input":"2021-12-03T11:05:03.714710Z","iopub.status.idle":"2021-12-03T11:05:04.494248Z","shell.execute_reply.started":"2021-12-03T11:05:03.714667Z","shell.execute_reply":"2021-12-03T11:05:04.493560Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train, x_val = train_test_split(d_train, test_size=0.33, random_state = 42)\nx_train = x_train.reset_index(drop=True)\nx_val = x_val.reset_index(drop=True)\n#print(x_val)\n#print(x_val.iloc[0,0])\nx_valImg = plt.imread(\"/kaggle/files/train/\"+x_val.iloc[0,0])\n#print(x_valImg[0])\nplt.imshow(x_valImg, cmap=plt.cm.binary)\nplt.show()\nprint(x_val['class'])","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:04.495893Z","iopub.execute_input":"2021-12-03T11:05:04.496312Z","iopub.status.idle":"2021-12-03T11:05:04.724911Z","shell.execute_reply.started":"2021-12-03T11:05:04.496269Z","shell.execute_reply":"2021-12-03T11:05:04.723859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_trainImg = plt.imread(\"/kaggle/files/train/\"+x_train.iloc[0,0])\nprint(x_trainImg[0])\nplt.imshow(x_trainImg, cmap = plt.cm.binary)\nplt.show()\nprint(x_train.shape)\nprint(x_train[\"class\"])","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:04.726737Z","iopub.execute_input":"2021-12-03T11:05:04.727033Z","iopub.status.idle":"2021-12-03T11:05:04.976915Z","shell.execute_reply.started":"2021-12-03T11:05:04.726997Z","shell.execute_reply":"2021-12-03T11:05:04.976255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagenerator=ImageDataGenerator(\n            horizontal_flip=True,\n            rescale=1./255\n)\n\nvalid_datagenerator=ImageDataGenerator(\n            rescale=1./255\n)\n\ntrain_generator = train_datagenerator.flow_from_dataframe(\n            x_train,\n            \"/kaggle/files/train/\",\n            x_col=\"file\",\n            y_col=\"class\",\n            target_size=(224,224),\n            class_mode=\"binary\"\n\n)\n\nvalid_generator=valid_datagenerator.flow_from_dataframe(\n            x_val,\n            \"/kaggle/files/train/\",\n            x_col=\"file\",\n            y_col=\"class\",\n            target_size=(224,224),\n            class_mode=\"binary\"\n)\nprint(type(valid_generator))","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:04.977859Z","iopub.execute_input":"2021-12-03T11:05:04.978740Z","iopub.status.idle":"2021-12-03T11:05:05.241675Z","shell.execute_reply.started":"2021-12-03T11:05:04.978687Z","shell.execute_reply":"2021-12-03T11:05:05.240989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image, labels = next(train_generator)\nprint(image.shape)\nprint(labels.shape)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:05.242709Z","iopub.execute_input":"2021-12-03T11:05:05.243135Z","iopub.status.idle":"2021-12-03T11:05:05.363729Z","shell.execute_reply.started":"2021-12-03T11:05:05.243103Z","shell.execute_reply":"2021-12-03T11:05:05.362789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plotImages(image):\n    fig, axes = plt.subplots(1, 6, figsize=(20,20))\n    axes = axes.flatten()\n    for ax, img in zip(axes, image):\n        ax.imshow(img)\n    plt.tight_layout()\n    plt.show()\n\nplotImages(image)\nprint(labels[:6])","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:05.365420Z","iopub.execute_input":"2021-12-03T11:05:05.365749Z","iopub.status.idle":"2021-12-03T11:05:06.608608Z","shell.execute_reply.started":"2021-12-03T11:05:05.365707Z","shell.execute_reply":"2021-12-03T11:05:06.607214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = plt.imread(\"/kaggle/files/train/dog.12493.jpg\")\nprint(img.shape)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:06.611327Z","iopub.execute_input":"2021-12-03T11:05:06.611585Z","iopub.status.idle":"2021-12-03T11:05:06.617560Z","shell.execute_reply.started":"2021-12-03T11:05:06.611555Z","shell.execute_reply":"2021-12-03T11:05:06.616777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = keras.Sequential()\n\nmodel.add(keras.layers.Conv2D(32, (3, 3), padding='same',input_shape=(224,224,3), activation='relu'))\nmodel.add(keras.layers.MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(keras.layers.Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(keras.layers.MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(keras.layers.Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(keras.layers.MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(keras.layers.Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(keras.layers.MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(keras.layers.Flatten())\nmodel.add(keras.layers.Dense(512, activation='relu'))\nmodel.add(keras.layers.Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='adam', loss=\"binary_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:06.618735Z","iopub.execute_input":"2021-12-03T11:05:06.619437Z","iopub.status.idle":"2021-12-03T11:05:06.755520Z","shell.execute_reply.started":"2021-12-03T11:05:06.619391Z","shell.execute_reply":"2021-12-03T11:05:06.754567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist = model.fit_generator(generator=train_generator, validation_data=valid_generator, epochs=5, steps_per_epoch=50)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:05:06.756848Z","iopub.execute_input":"2021-12-03T11:05:06.757080Z","iopub.status.idle":"2021-12-03T11:16:12.291020Z","shell.execute_reply.started":"2021-12-03T11:05:06.757051Z","shell.execute_reply":"2021-12-03T11:16:12.290098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist.history","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:16:12.292448Z","iopub.execute_input":"2021-12-03T11:16:12.292802Z","iopub.status.idle":"2021-12-03T11:16:12.298365Z","shell.execute_reply.started":"2021-12-03T11:16:12.292766Z","shell.execute_reply":"2021-12-03T11:16:12.297794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_test_col = []\nfor file in test_img:\n    x_test_col.append(file)\n\nx_test = pd.DataFrame({'filename': x_test_col})\ntest_generator = valid_datagenerator.flow_from_dataframe(x_test,\n                                             directory = \"/kaggle/files/test1\",\n                                             x_col = \"filename\",\n                                             y_col = None,\n                                             class_mode = None,\n                                             target_size = (224,224))","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:16:12.299560Z","iopub.execute_input":"2021-12-03T11:16:12.300194Z","iopub.status.idle":"2021-12-03T11:16:12.419420Z","shell.execute_reply.started":"2021-12-03T11:16:12.300156Z","shell.execute_reply":"2021-12-03T11:16:12.418476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions=model.predict(test_generator)\npredictions.size","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:16:12.420858Z","iopub.execute_input":"2021-12-03T11:16:12.421127Z","iopub.status.idle":"2021-12-03T11:18:05.872140Z","shell.execute_reply.started":"2021-12-03T11:16:12.421097Z","shell.execute_reply":"2021-12-03T11:18:05.871194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(type(predictions))\nprint(len(predictions))\ni = random.randint(0,len(predictions))\nprint(predictions[i])\nif predictions[i] > 0.5:\n    print(\"Dog\")\nelse:\n    print(\"Cat\")\n\nimage = plt.imread(\"/kaggle/files/test1/\"+test_img[i])\n\nplt.imshow(image, cmap=plt.cm.binary)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:18:05.873924Z","iopub.execute_input":"2021-12-03T11:18:05.874589Z","iopub.status.idle":"2021-12-03T11:18:06.150371Z","shell.execute_reply.started":"2021-12-03T11:18:05.874543Z","shell.execute_reply":"2021-12-03T11:18:06.147929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = []\nfor i in range(len(predictions)):\n    if predictions[i] > 0.5:\n        pred.append(1)\n    else:\n        pred.append(0)\n","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:18:06.152168Z","iopub.execute_input":"2021-12-03T11:18:06.152707Z","iopub.status.idle":"2021-12-03T11:18:06.182746Z","shell.execute_reply.started":"2021-12-03T11:18:06.152653Z","shell.execute_reply":"2021-12-03T11:18:06.181958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output = pd.DataFrame({\"Id\": np.arange(1,12501), \"label\": pred})\noutput.to_csv(\"/kaggle/working/submission.csv\", index = False)\n\nprint(output)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T11:18:06.185965Z","iopub.execute_input":"2021-12-03T11:18:06.186243Z","iopub.status.idle":"2021-12-03T11:18:06.218905Z","shell.execute_reply.started":"2021-12-03T11:18:06.186210Z","shell.execute_reply":"2021-12-03T11:18:06.218271Z"},"trusted":true},"execution_count":null,"outputs":[]}]}