{"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)\nfrom zipfile import ZipFile\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":"2023-07-29T03:00:14.513129Z","iopub.execute_input":"2023-07-29T03:00:14.513528Z","iopub.status.idle":"2023-07-29T03:00:14.548810Z","shell.execute_reply.started":"2023-07-29T03:00:14.513497Z","shell.execute_reply":"2023-07-29T03:00:14.547588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nimport cv2\nimport random\nimport pickle\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2023-07-29T03:00:14.551390Z","iopub.execute_input":"2023-07-29T03:00:14.551754Z","iopub.status.idle":"2023-07-29T03:00:15.400347Z","shell.execute_reply.started":"2023-07-29T03:00:14.551723Z","shell.execute_reply":"2023-07-29T03:00:15.399184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D","metadata":{"execution":{"iopub.status.busy":"2023-07-29T03:00:15.401655Z","iopub.execute_input":"2023-07-29T03:00:15.402028Z","iopub.status.idle":"2023-07-29T03:00:24.501796Z","shell.execute_reply.started":"2023-07-29T03:00:15.401994Z","shell.execute_reply":"2023-07-29T03:00:24.500661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip', 'r') as zip:\n    #zip.printdir()\n    zip.extractall()\n    print('done')","metadata":{"execution":{"iopub.status.busy":"2023-07-29T03:00:24.504529Z","iopub.execute_input":"2023-07-29T03:00:24.505252Z","iopub.status.idle":"2023-07-29T03:00:36.275089Z","shell.execute_reply.started":"2023-07-29T03:00:24.505213Z","shell.execute_reply":"2023-07-29T03:00:36.273766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip', 'r') as zip:\n    #zip.printdir()\n    zip.extractall()\n    print('done')","metadata":{"execution":{"iopub.status.busy":"2023-07-29T03:00:36.276503Z","iopub.execute_input":"2023-07-29T03:00:36.276883Z","iopub.status.idle":"2023-07-29T03:00:42.150981Z","shell.execute_reply.started":"2023-07-29T03:00:36.276852Z","shell.execute_reply":"2023-07-29T03:00:42.149574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"PATH = '/kaggle/working/train'\nfilename = os.listdir(PATH)\nIMG_SIZE = 100\n\nplt.figure(figsize=(10,10))\nfor i in range(1, 7):\n    img_array = cv2.imread(os.path.join(PATH, filename[i]))\n    resize_image = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))\n    plt.subplot(3,3, i)\n    image = cv2.cvtColor(resize_image, cv2.COLOR_BGR2RGB)\n    #plt.figure()\n    plt.axis('off')\n    plt.imshow(image)","metadata":{"execution":{"iopub.status.busy":"2023-07-29T03:00:42.152709Z","iopub.execute_input":"2023-07-29T03:00:42.153167Z","iopub.status.idle":"2023-07-29T03:00:42.802684Z","shell.execute_reply.started":"2023-07-29T03:00:42.153135Z","shell.execute_reply":"2023-07-29T03:00:42.801353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_data = []\nIMG_SIZE = 100\npath = '/kaggle/working/train'\nfilenames = os.listdir('/kaggle/working/train')\nfor img in tqdm(filenames):\n    try:\n        if img.find('cat') == -1:\n            category = 0\n        else:\n            category = 1\n        \n        img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)\n        new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))\n        training_data.append([new_array, category])\n    except Exception as e:\n        pass","metadata":{"execution":{"iopub.status.busy":"2023-07-29T03:00:42.804050Z","iopub.execute_input":"2023-07-29T03:00:42.804483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,10))\nfor i in range(1, 7):\n    plt.subplot(3,3,i)\n    plt.axis('off')\n    if training_data[10+i][1] == 0:\n        plt.title('Dog')\n    else:\n        plt.title('Cat')\n    plt.imshow(training_data[10+i][0], cmap='gray_r')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"testing_data = []\nIMG_SIZE = 100\n\npath = '/kaggle/working/test'\nfilenames = os.listdir('/kaggle/working/test')\nfor img in tqdm(filenames):\n    try:        \n        img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)\n        new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))\n        testing_data.append([new_array])\n    except Exception as e:\n        pass","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(training_data)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"random.shuffle(training_data)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = []\ny = []\n\nfor features, label  in training_data:\n    X.append(features)\n    y.append(label)\n    \nX = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pickle_out =open(\"X.pickle\", \"wb\")\npickle.dump(X, pickle_out)\npickle_out.close()\n\npickle_out = open(\"y.pickle\", \"wb\")\npickle.dump(y, pickle_out)\npickle_out.close()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pickle_in = open(\"X.pickle\", \"rb\")\nX = pickle.load(pickle_in)\n\npickle_in = open(\"y.pickle\", \"rb\")\ny = pickle.load(pickle_in)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = X/255.0\n\nX = np.array(X)\ny = np.array(y)\nlen(X)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(y)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=50)\nlen(X_train)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(y_train)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(256, (3,3), input_shape=X_train.shape[1:]))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(256, (3,3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors\n\nmodel.add(Dense(64))\nmodel.add(Dense(1))\n\nmodel.add(Activation('sigmoid'))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'],)\n\nhistory = model.fit(X_train, y_train, batch_size=32, epochs=15, validation_data = (x_test, y_test))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score = model.evaluate(x_test, y_test, verbose=0)\nprint('Test Loss:', score[0])\nprint('Test accuracy:', score[1])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plotting our loss charts\n# Use the history object we created to get our saved perormace result.\nhistory_dict = history.history\n\n# Extract the loss and validation losses\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\n\nepochs = range(1, len(loss_values)+1)\n\nline1 = plt.plot(epochs, val_loss_values, label ='Validation/Test Loss')\nline2 = plt.plot(epochs, loss_values, label='Training Loss')\nplt.setp(line1, linewidth = 2.0, marker='+', markersize=10.0)\nplt.setp(line2, linewidth=2.0, marker='4', markersize=10.0)\nplt.legend()\nplt.grid(True)\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_dict = history.history\n\nacc_values = history_dict['accuracy']\nval_acc_values = history_dict['val_accuracy']\nepochs = range(1, len(loss_values)+1)\n\nline1 = plt.plot(epochs, val_loss_values, label='Validation/Test Accuracy')\nline2 = plt.plot(epochs, acc_values, label ='Training Accuracy')\n\nplt.setp(line1, linewidth=2.0, marker='+', markersize=10.0)\nplt.setp(line2, linewidth=2.0, marker='4', markersize=10.0)\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.grid(True)\nplt.legend()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SIZE = 100\ntest = []\n\nfor features  in testing_data:\n    test.append(features)\n    \ntest = np.array(test).reshape(-1, IMG_SIZE, IMG_SIZE, 1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = test/255.0\n\ntest = np.array(test)\nprediction = model.predict(test) \n#predict_xtest = model.predict(x_test) \n#predict_xtest \nprediction","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"prediction.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"my_submission = pd.read_csv('/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv')\nmy_submission.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"my_submission['label'] = prediction\nmy_submission['label'] = my_submission['label'].map(lambda x: 1 if x >= 0.5 else 0 )\nmy_submission.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"my_submission['label'] = my_submission['label'].round(1)\nmy_submission.to_csv('my_submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}