{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30776,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"### Importing Libraries","metadata":{}},{"cell_type":"code","source":"import zipfile\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport io\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay\nimport seaborn as sns","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-10-17T11:03:04.625458Z","iopub.execute_input":"2024-10-17T11:03:04.625758Z","iopub.status.idle":"2024-10-17T11:03:26.439392Z","shell.execute_reply.started":"2024-10-17T11:03:04.625724Z","shell.execute_reply":"2024-10-17T11:03:26.438684Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Load Dataset","metadata":{}},{"cell_type":"code","source":"zip_train_path = '/kaggle/input/dogs-vs-cats/train.zip'\nzip_test_path = '/kaggle/input/dogs-vs-cats/test1.zip'","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:26.441454Z","iopub.execute_input":"2024-10-17T11:03:26.442380Z","iopub.status.idle":"2024-10-17T11:03:26.446208Z","shell.execute_reply.started":"2024-10-17T11:03:26.442311Z","shell.execute_reply":"2024-10-17T11:03:26.445308Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Data Visualization\ndef visualize(input_zip, num_images=10):\n    with zipfile.ZipFile(input_zip, 'r') as archive_zip:\n        archives = archive_zip.namelist()\n        \n        images = [archive for archive in archives if archive.endswith(('.png', '.jpg', '.jpeg'))]\n        \n        for i, img_path in enumerate(images[:num_images]):\n            with archive_zip.open(img_path) as image_zip:\n                img = Image.open(io.BytesIO(image_zip.read()))\n                plt.subplot(1, num_images, i + 1)\n                plt.imshow(img) \n                plt.axis('off')\n\n        plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:26.447119Z","iopub.execute_input":"2024-10-17T11:03:26.447396Z","iopub.status.idle":"2024-10-17T11:03:26.464284Z","shell.execute_reply.started":"2024-10-17T11:03:26.447357Z","shell.execute_reply":"2024-10-17T11:03:26.463596Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# train data\nvisualize(zip_train_path, num_images=10)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:26.465305Z","iopub.execute_input":"2024-10-17T11:03:26.465613Z","iopub.status.idle":"2024-10-17T11:03:27.403212Z","shell.execute_reply.started":"2024-10-17T11:03:26.465582Z","shell.execute_reply":"2024-10-17T11:03:27.402174Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test data\nvisualize(zip_test_path, num_images=10)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:27.405985Z","iopub.execute_input":"2024-10-17T11:03:27.406313Z","iopub.status.idle":"2024-10-17T11:03:28.105811Z","shell.execute_reply.started":"2024-10-17T11:03:27.406278Z","shell.execute_reply":"2024-10-17T11:03:28.104868Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Rescaling","metadata":{}},{"cell_type":"code","source":"new_size = (128, 128)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:28.107068Z","iopub.execute_input":"2024-10-17T11:03:28.107499Z","iopub.status.idle":"2024-10-17T11:03:28.112088Z","shell.execute_reply.started":"2024-10-17T11:03:28.107452Z","shell.execute_reply":"2024-10-17T11:03:28.111025Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def resize(input_zip, num_images=10, size=new_size):\n    with zipfile.ZipFile(input_zip, 'r') as archive_zip:\n        archives = archive_zip.namelist()\n        images = [archive for archive in archives if archive.endswith(('.png', '.jpg', '.jpeg'))]\n        \n        for i, img_path in enumerate(images[:num_images]):\n            with archive_zip.open(img_path) as image_zip:\n                img = Image.open(io.BytesIO(image_zip.read()))\n                img = img.convert('L')\n                img = img.resize(size)\n                \n                plt.subplot(1, num_images, i + 1)\n                plt.imshow(img, cmap='gray') \n                plt.axis('off') \n\n        plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:28.113286Z","iopub.execute_input":"2024-10-17T11:03:28.113605Z","iopub.status.idle":"2024-10-17T11:03:28.124320Z","shell.execute_reply.started":"2024-10-17T11:03:28.113573Z","shell.execute_reply":"2024-10-17T11:03:28.123618Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"resize(zip_train_path, num_images=10, size=(128, 128))","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:28.125505Z","iopub.execute_input":"2024-10-17T11:03:28.125826Z","iopub.status.idle":"2024-10-17T11:03:28.930000Z","shell.execute_reply.started":"2024-10-17T11:03:28.125793Z","shell.execute_reply":"2024-10-17T11:03:28.928455Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"resize(zip_test_path, num_images=10, size=(128, 128))","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:28.932020Z","iopub.execute_input":"2024-10-17T11:03:28.932625Z","iopub.status.idle":"2024-10-17T11:03:29.404875Z","shell.execute_reply.started":"2024-10-17T11:03:28.932562Z","shell.execute_reply":"2024-10-17T11:03:29.403577Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Count dataset size\ndef count(input_zip):\n    with zipfile.ZipFile(input_zip, 'r') as archive_zip:\n        archives = archive_zip.namelist()\n        \n        images = [archive for archive in archives if archive.endswith(('.png', '.jpg', '.jpeg'))]\n        \n        num_images = len(images)\n        print(f\"Images in {input_zip}: {num_images}\")","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:29.406824Z","iopub.execute_input":"2024-10-17T11:03:29.407761Z","iopub.status.idle":"2024-10-17T11:03:29.416827Z","shell.execute_reply.started":"2024-10-17T11:03:29.407697Z","shell.execute_reply":"2024-10-17T11:03:29.415002Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"count(zip_train_path)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:29.418661Z","iopub.execute_input":"2024-10-17T11:03:29.419251Z","iopub.status.idle":"2024-10-17T11:03:29.710832Z","shell.execute_reply.started":"2024-10-17T11:03:29.419192Z","shell.execute_reply":"2024-10-17T11:03:29.709926Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"count(zip_test_path)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:29.711949Z","iopub.execute_input":"2024-10-17T11:03:29.712255Z","iopub.status.idle":"2024-10-17T11:03:29.839036Z","shell.execute_reply.started":"2024-10-17T11:03:29.712222Z","shell.execute_reply":"2024-10-17T11:03:29.838172Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Preprocess images by converting to grayscale and resizing","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:29.840167Z","iopub.execute_input":"2024-10-17T11:03:29.840550Z","iopub.status.idle":"2024-10-17T11:03:29.844792Z","shell.execute_reply.started":"2024-10-17T11:03:29.840505Z","shell.execute_reply":"2024-10-17T11:03:29.843937Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"new_size = (128, 128)\n\ndef preprocess(input_zip, size=new_size):\n    images_processed = []\n    \n    with zipfile.ZipFile(input_zip, 'r') as archive_zip:\n        archives = archive_zip.namelist()\n        \n        images = [archive for archive in archives if archive.endswith(('.png', '.jpg', '.jpeg'))]\n        \n        for img_path in images:\n            with archive_zip.open(img_path) as image_zip:\n                img = Image.open(io.BytesIO(image_zip.read()))\n                \n                img = img.convert('L')\n                \n                img = img.resize(size)\n                \n                img_array = np.array(img) / 255.0\n                \n                images_processed.append(img_array)\n    \n    dataset = np.array(images_processed)\n    \n    return dataset","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:29.848895Z","iopub.execute_input":"2024-10-17T11:03:29.849174Z","iopub.status.idle":"2024-10-17T11:03:29.856715Z","shell.execute_reply.started":"2024-10-17T11:03:29.849143Z","shell.execute_reply":"2024-10-17T11:03:29.855958Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataset = preprocess(zip_train_path, new_size)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:03:29.857624Z","iopub.execute_input":"2024-10-17T11:03:29.857924Z","iopub.status.idle":"2024-10-17T11:04:31.975754Z","shell.execute_reply.started":"2024-10-17T11:03:29.857893Z","shell.execute_reply":"2024-10-17T11:04:31.974973Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dataset = preprocess(zip_test_path, new_size)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:04:31.977027Z","iopub.execute_input":"2024-10-17T11:04:31.977771Z","iopub.status.idle":"2024-10-17T11:05:02.437304Z","shell.execute_reply.started":"2024-10-17T11:04:31.977724Z","shell.execute_reply":"2024-10-17T11:05:02.436386Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataset","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:05:02.439047Z","iopub.execute_input":"2024-10-17T11:05:02.439475Z","iopub.status.idle":"2024-10-17T11:05:02.448872Z","shell.execute_reply.started":"2024-10-17T11:05:02.439428Z","shell.execute_reply":"2024-10-17T11:05:02.447831Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# extract class tags\ndef extract_tags(input_zip):\n    results = []\n    with zipfile.ZipFile(input_zip, 'r') as archive_zip:\n        archives = archive_zip.namelist()\n        \n        images = [archive for archive in archives if archive.endswith(('.png', '.jpg', '.jpeg'))]\n        \n        for img_path in images:\n            if 'dog' in img_path.lower():\n                results.append(('dog', img_path))\n            elif 'cat' in img_path.lower():\n                results.append(('cat', img_path))\n            else:\n                results.append(('unknown', img_path))  # Si no es identificable\n        \n    return results","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:05:02.450127Z","iopub.execute_input":"2024-10-17T11:05:02.450474Z","iopub.status.idle":"2024-10-17T11:05:02.459941Z","shell.execute_reply.started":"2024-10-17T11:05:02.450437Z","shell.execute_reply":"2024-10-17T11:05:02.459108Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_labels = extract_tags(zip_train_path)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:05:02.461125Z","iopub.execute_input":"2024-10-17T11:05:02.461441Z","iopub.status.idle":"2024-10-17T11:05:02.743735Z","shell.execute_reply.started":"2024-10-17T11:05:02.461409Z","shell.execute_reply":"2024-10-17T11:05:02.742771Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for label, img_path in train_labels[:10]:\n    print(f\"Image: {img_path}, Label: {label}\")","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:05:02.744893Z","iopub.execute_input":"2024-10-17T11:05:02.745197Z","iopub.status.idle":"2024-10-17T11:05:02.750368Z","shell.execute_reply.started":"2024-10-17T11:05:02.745164Z","shell.execute_reply":"2024-10-17T11:05:02.749281Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Building Model","metadata":{}},{"cell_type":"code","source":"train_binary = np.array([1 if label == 'dog' else 0 for label, _ in train_labels])\n\ntrain_dataset = np.expand_dims(train_dataset, axis=-1)\n\n# Train split\nX_train, X_temp, y_train, y_temp = train_test_split(train_dataset, train_binary, test_size=0.2, random_state=42)\n\n# Validation-Test Split\nX_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:05:02.751662Z","iopub.execute_input":"2024-10-17T11:05:02.752037Z","iopub.status.idle":"2024-10-17T11:05:03.638564Z","shell.execute_reply.started":"2024-10-17T11:05:02.751979Z","shell.execute_reply":"2024-10-17T11:05:03.637763Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create Model\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 1)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:05:03.640131Z","iopub.execute_input":"2024-10-17T11:05:03.640556Z","iopub.status.idle":"2024-10-17T11:05:04.760027Z","shell.execute_reply.started":"2024-10-17T11:05:03.640511Z","shell.execute_reply":"2024-10-17T11:05:04.759097Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:05:04.761428Z","iopub.execute_input":"2024-10-17T11:05:04.761833Z","iopub.status.idle":"2024-10-17T11:05:04.775425Z","shell.execute_reply.started":"2024-10-17T11:05:04.761788Z","shell.execute_reply":"2024-10-17T11:05:04.774664Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train the model\nhistory = model.fit(X_train, y_train, epochs=10, validation_data=(X_val, y_val))","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:05:04.776488Z","iopub.execute_input":"2024-10-17T11:05:04.776776Z","iopub.status.idle":"2024-10-17T11:06:42.354323Z","shell.execute_reply.started":"2024-10-17T11:05:04.776745Z","shell.execute_reply":"2024-10-17T11:06:42.353390Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.figure(figsize=(12, 6))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title('Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(loc='upper left')\n\n# Plot training & validation loss values\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Model Loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(loc='upper left')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:06:42.355785Z","iopub.execute_input":"2024-10-17T11:06:42.356109Z","iopub.status.idle":"2024-10-17T11:06:43.003992Z","shell.execute_reply.started":"2024-10-17T11:06:42.356074Z","shell.execute_reply":"2024-10-17T11:06:43.003131Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Model Evaluation","metadata":{}},{"cell_type":"code","source":"loss, accuracy = model.evaluate(X_val, y_val)\nprint(f'Accuracy: {accuracy:.4f}')\nprint(f'Loss: {loss:.4f}')","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:06:43.005060Z","iopub.execute_input":"2024-10-17T11:06:43.005371Z","iopub.status.idle":"2024-10-17T11:06:43.883237Z","shell.execute_reply.started":"2024-10-17T11:06:43.005312Z","shell.execute_reply":"2024-10-17T11:06:43.882443Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Evaluate on Test Set","metadata":{}},{"cell_type":"code","source":"loss, accuracy = model.evaluate(X_test, y_test)\nprint(f'Accuracy: {accuracy:.4f}')\nprint(f'Loss: {loss:.4f}')","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:06:43.884293Z","iopub.execute_input":"2024-10-17T11:06:43.884646Z","iopub.status.idle":"2024-10-17T11:06:44.748903Z","shell.execute_reply.started":"2024-10-17T11:06:43.884612Z","shell.execute_reply":"2024-10-17T11:06:44.748032Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Confusion Matrix\ny_pred = model.predict(X_test)\ny_pred = (y_pred > 0.5).astype(int)\ncm = confusion_matrix(y_test, y_pred)\nplt.figure(figsize=(8, 6))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False, \n            xticklabels=['Class 0', 'Class 1'], yticklabels=['Class 0', 'Class 1'])\nplt.xlabel('Predicted Labels')\nplt.ylabel('True Labels')\nplt.title('Confusion Matrix')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:06:44.750134Z","iopub.execute_input":"2024-10-17T11:06:44.750619Z","iopub.status.idle":"2024-10-17T11:06:46.141790Z","shell.execute_reply.started":"2024-10-17T11:06:44.750574Z","shell.execute_reply":"2024-10-17T11:06:46.140352Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# few random predictions\nnum_samples = 5  # Number of samples to display\nrandom_indices = np.random.choice(len(X_test), num_samples, replace=False)\nplt.figure(figsize=(15, 5))\nfor i, idx in enumerate(random_indices):\n    plt.subplot(1, num_samples, i + 1)\n    plt.imshow(X_test[idx].reshape(128, 128), cmap='gray')  # Reshape for display and use grayscale\n    true_label = 'dog' if y_test[idx] == 1 else 'cat'  # True label\n    pred_label = 'dog' if y_pred[idx][0] == 1 else 'cat'  # Predicted label\n    plt.title(f'True: {true_label}\\nPred: {pred_label}')\n    plt.axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-17T11:06:46.143592Z","iopub.execute_input":"2024-10-17T11:06:46.144129Z","iopub.status.idle":"2024-10-17T11:06:46.786745Z","shell.execute_reply.started":"2024-10-17T11:06:46.144068Z","shell.execute_reply":"2024-10-17T11:06:46.785819Z"},"trusted":true},"outputs":[],"execution_count":null}]}