{"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 the files in the input directory\nimport cv2\nimport random\nimport os\nimport shutil\n\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\nfrom keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f08abde246bc6f334aedab5b76cfdea2e5ebab31"},"cell_type":"code","source":"# constant values\nVALID_SPLIT = 0.2\nIMG_SIZE = 64\nBATCH_SIZE = 128\nCHANNEL = 1\n\n# iterate over train file\n\nlabel = []\ndata = []\ncounter = 0\n\ndata_path = \"../input/train/train\"\n\nfor img in os.listdir(data_path):\n    img_data = cv2.imread(os.path.join(data_path, img), cv2.IMREAD_GRAYSCALE)\n    img_data = cv2.resize(img_data, (IMG_SIZE, IMG_SIZE))\n    if img.startswith(\"cat\"):\n        label.append(0)\n    elif img.startswith(\"dog\"):\n        label.append(1)\n    try:\n        data.append(img_data/255)\n    except:\n        label = label[:len(label)-1]\n\n    counter += 1\n    if counter % 1000 == 0:\n        print(f\"Image data retrieved: {counter}\")\n\ndata = np.array(data)\ndata = data.reshape((data.shape)[0], (data.shape)[1], (data.shape)[2], 1)\nlabel = np.array(label)\n\nprint(f\"data shape: {data.shape}\")\nprint(f\"label shape: {label.shape}\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5cae6ccb493947ebe0f111f4606e9914463b1da9"},"cell_type":"code","source":"from keras.layers import Dropout","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"30891d1edd3f344dcfbcb9221d45b958d25312c1"},"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(8, (3, 3), input_shape=(IMG_SIZE, IMG_SIZE, CHANNEL),\n                 activation='relu', padding='same'))\nmodel.add(MaxPooling2D())\n\nmodel.add(Conv2D(16, (3, 3), activation='relu', padding='same'))\nmodel.add(MaxPooling2D())\n\nmodel.add(Conv2D(32, (3, 3), activation='relu', padding='same'))\nmodel.add(MaxPooling2D())\n\nmodel.add(Conv2D(64, (3, 3), activation='relu', padding='same'))\nmodel.add(MaxPooling2D())\n\nmodel.add(Flatten())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\n\n\n# compile\nmodel.compile(optimizer='adam', loss='binary_crossentropy',\n              metrics=['accuracy'])\n\nmodel.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e5e918714ff0d4892710536289206dee8e71415a"},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint\n\ncallback_save = ModelCheckpoint(\"model.h5\",\n                                monitor='val_loss',\n                                verbose=0,\n                                save_weights_only=True,\n                                mode='auto',\n                                save_best_only=True)\n\n# alternate\ndatagen = ImageDataGenerator(\n    featurewise_center=True,\n    featurewise_std_normalization=True,\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    horizontal_flip=True)\n\ndatagen.fit(data)\n\ntrain_history = model.fit_generator(\n    datagen.flow(data, label, batch_size=BATCH_SIZE),\n    steps_per_epoch=len(data) / BATCH_SIZE,\n    epochs=10,\n    callbacks=[callback_save])\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# test data\ntest_data=[]\nid=[]\ncounter=0\nfor file in os.listdir(\"../input/test1/test1\"):\n    img_data=cv2.imread(os.path.join(\"../input/test1/test1\",file), cv2.IMREAD_GRAYSCALE)\n    try:\n        img_data=cv2.resize(img_data,(IMG_SIZE,IMG_SIZE))\n        test_data.append(img_data/255)\n        id.append((file.split(\".\"))[0])\n    except:\n        print (f\"Doesn't work\")\n    counter+=1\n    if counter%3000==0:\n        print (f\"Image Retreived: {counter}\")\n\ntest_data=np.array(test_data)\nprint (test_data.shape)\ntest_data=test_data.reshape((test_data.shape)[0],(test_data.shape)[1],(test_data.shape)[2],1)\ndf_submission=pd.DataFrame({\"id\":id})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"aa24ccd3af1d2813e99e7189bef9b7ca31445f40"},"cell_type":"code","source":"preds=model.predict(test_data)\npreds=np.round(preds,decimals=2)\nlabels=[1 if value>0.5 else 0 for value in preds]\n\ndf_submission[\"label\"]=labels\ndf_submission.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ca09fc41fd46c290dabfc02dc3bb0835b336529a"},"cell_type":"code","source":"df_submission.to_csv(\"cnn_submission.csv\",index=False)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e5b326ca831aed878214908da57e05aff35e500c"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}