{"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-15T17:12:58.462467Z","iopub.execute_input":"2024-10-15T17:12:58.462871Z","iopub.status.idle":"2024-10-15T17:13:11.373353Z","shell.execute_reply.started":"2024-10-15T17:12:58.462833Z","shell.execute_reply":"2024-10-15T17:13:11.372552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:13:11.375268Z","iopub.execute_input":"2024-10-15T17:13:11.375778Z","iopub.status.idle":"2024-10-15T17:13:11.380040Z","shell.execute_reply.started":"2024-10-15T17:13:11.375744Z","shell.execute_reply":"2024-10-15T17:13:11.379032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:13:11.381251Z","iopub.execute_input":"2024-10-15T17:13:11.381620Z","iopub.status.idle":"2024-10-15T17:13:11.410587Z","shell.execute_reply.started":"2024-10-15T17:13:11.381573Z","shell.execute_reply":"2024-10-15T17:13:11.409768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train data\nvisualize(zip_train_path, num_images=10)","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:13:11.411949Z","iopub.execute_input":"2024-10-15T17:13:11.412230Z","iopub.status.idle":"2024-10-15T17:13:12.263343Z","shell.execute_reply.started":"2024-10-15T17:13:11.412199Z","shell.execute_reply":"2024-10-15T17:13:12.262341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test data\nvisualize(zip_test_path, num_images=10)","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:13:12.265693Z","iopub.execute_input":"2024-10-15T17:13:12.266010Z","iopub.status.idle":"2024-10-15T17:13:12.941775Z","shell.execute_reply.started":"2024-10-15T17:13:12.265976Z","shell.execute_reply":"2024-10-15T17:13:12.940838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Rescaling","metadata":{}},{"cell_type":"code","source":"new_size = (128, 128)","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:13:12.942852Z","iopub.execute_input":"2024-10-15T17:13:12.943136Z","iopub.status.idle":"2024-10-15T17:13:12.947344Z","shell.execute_reply.started":"2024-10-15T17:13:12.943106Z","shell.execute_reply":"2024-10-15T17:13:12.946472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:13:12.948404Z","iopub.execute_input":"2024-10-15T17:13:12.948740Z","iopub.status.idle":"2024-10-15T17:13:12.958118Z","shell.execute_reply.started":"2024-10-15T17:13:12.948708Z","shell.execute_reply":"2024-10-15T17:13:12.957206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"resize(zip_train_path, num_images=10, size=(128, 128))","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:13:12.959182Z","iopub.execute_input":"2024-10-15T17:13:12.959463Z","iopub.status.idle":"2024-10-15T17:13:13.789380Z","shell.execute_reply.started":"2024-10-15T17:13:12.959433Z","shell.execute_reply":"2024-10-15T17:13:13.785058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"resize(zip_test_path, num_images=10, size=(128, 128))","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:13:13.791513Z","iopub.execute_input":"2024-10-15T17:13:13.792110Z","iopub.status.idle":"2024-10-15T17:13:14.261662Z","shell.execute_reply.started":"2024-10-15T17:13:13.792051Z","shell.execute_reply":"2024-10-15T17:13:14.260193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:13:14.263575Z","iopub.execute_input":"2024-10-15T17:13:14.264329Z","iopub.status.idle":"2024-10-15T17:13:14.272886Z","shell.execute_reply.started":"2024-10-15T17:13:14.264267Z","shell.execute_reply":"2024-10-15T17:13:14.271712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count(zip_train_path)","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:13:14.274829Z","iopub.execute_input":"2024-10-15T17:13:14.275702Z","iopub.status.idle":"2024-10-15T17:13:14.555926Z","shell.execute_reply.started":"2024-10-15T17:13:14.275618Z","shell.execute_reply":"2024-10-15T17:13:14.554990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count(zip_test_path)","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:13:14.557039Z","iopub.execute_input":"2024-10-15T17:13:14.557417Z","iopub.status.idle":"2024-10-15T17:13:14.687039Z","shell.execute_reply.started":"2024-10-15T17:13:14.557364Z","shell.execute_reply":"2024-10-15T17:13:14.686153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Preprocess images by converting to grayscale and resizing","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:13:14.688054Z","iopub.execute_input":"2024-10-15T17:13:14.688347Z","iopub.status.idle":"2024-10-15T17:13:14.692151Z","shell.execute_reply.started":"2024-10-15T17:13:14.688316Z","shell.execute_reply":"2024-10-15T17:13:14.691173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:13:14.696299Z","iopub.execute_input":"2024-10-15T17:13:14.696607Z","iopub.status.idle":"2024-10-15T17:13:14.704977Z","shell.execute_reply.started":"2024-10-15T17:13:14.696575Z","shell.execute_reply":"2024-10-15T17:13:14.703981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = preprocess(zip_train_path, new_size)","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:13:14.706063Z","iopub.execute_input":"2024-10-15T17:13:14.706414Z","iopub.status.idle":"2024-10-15T17:14:12.932860Z","shell.execute_reply.started":"2024-10-15T17:13:14.706372Z","shell.execute_reply":"2024-10-15T17:14:12.931813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dataset = preprocess(zip_test_path, new_size)","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:14:12.934230Z","iopub.execute_input":"2024-10-15T17:14:12.934544Z","iopub.status.idle":"2024-10-15T17:14:41.453730Z","shell.execute_reply.started":"2024-10-15T17:14:12.934511Z","shell.execute_reply":"2024-10-15T17:14:41.452873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:14:41.455016Z","iopub.execute_input":"2024-10-15T17:14:41.455347Z","iopub.status.idle":"2024-10-15T17:14:41.464384Z","shell.execute_reply.started":"2024-10-15T17:14:41.455313Z","shell.execute_reply":"2024-10-15T17:14:41.463504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:14:41.465585Z","iopub.execute_input":"2024-10-15T17:14:41.465908Z","iopub.status.idle":"2024-10-15T17:14:41.477649Z","shell.execute_reply.started":"2024-10-15T17:14:41.465877Z","shell.execute_reply":"2024-10-15T17:14:41.476879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels = extract_tags(zip_train_path)","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:14:41.479459Z","iopub.execute_input":"2024-10-15T17:14:41.479785Z","iopub.status.idle":"2024-10-15T17:14:41.784565Z","shell.execute_reply.started":"2024-10-15T17:14:41.479753Z","shell.execute_reply":"2024-10-15T17:14:41.783691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:14:41.785891Z","iopub.execute_input":"2024-10-15T17:14:41.786322Z","iopub.status.idle":"2024-10-15T17:14:41.792382Z","shell.execute_reply.started":"2024-10-15T17:14:41.786266Z","shell.execute_reply":"2024-10-15T17:14:41.791418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:14:41.793709Z","iopub.execute_input":"2024-10-15T17:14:41.794033Z","iopub.status.idle":"2024-10-15T17:14:42.651678Z","shell.execute_reply.started":"2024-10-15T17:14:41.793997Z","shell.execute_reply":"2024-10-15T17:14:42.650867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create Model\nmodel = Sequential()\n\n# Layer 1: Convolution+Max Pooling\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 1)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n# Layer 2: Convolution+Max Pooling\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n# Layer 3: Convolution+Max Pooling\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n# Ftatten Layer\nmodel.add(Flatten())\n\n# Dense Layer\nmodel.add(Dense(128, activation='relu'))\n\n# Output Layer for binary classification\nmodel.add(Dense(1, activation='sigmoid'))","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:14:42.652920Z","iopub.execute_input":"2024-10-15T17:14:42.653235Z","iopub.status.idle":"2024-10-15T17:14:43.544907Z","shell.execute_reply.started":"2024-10-15T17:14:42.653202Z","shell.execute_reply":"2024-10-15T17:14:43.543886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-10-15T17:14:43.546362Z","iopub.execute_input":"2024-10-15T17:14:43.546801Z","iopub.status.idle":"2024-10-15T17:14:43.560824Z","shell.execute_reply.started":"2024-10-15T17:14:43.546754Z","shell.execute_reply":"2024-10-15T17:14:43.560038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:14:43.561836Z","iopub.execute_input":"2024-10-15T17:14:43.562094Z","iopub.status.idle":"2024-10-15T17:16:16.326027Z","shell.execute_reply.started":"2024-10-15T17:14:43.562065Z","shell.execute_reply":"2024-10-15T17:16:16.324984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:16:16.328294Z","iopub.execute_input":"2024-10-15T17:16:16.328623Z","iopub.status.idle":"2024-10-15T17:16:16.893003Z","shell.execute_reply.started":"2024-10-15T17:16:16.328582Z","shell.execute_reply":"2024-10-15T17:16:16.892061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:16:16.894173Z","iopub.execute_input":"2024-10-15T17:16:16.894448Z","iopub.status.idle":"2024-10-15T17:16:17.731514Z","shell.execute_reply.started":"2024-10-15T17:16:16.894417Z","shell.execute_reply":"2024-10-15T17:16:17.730521Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Evaluat 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-15T17:16:17.732784Z","iopub.execute_input":"2024-10-15T17:16:17.733243Z","iopub.status.idle":"2024-10-15T17:16:18.577624Z","shell.execute_reply.started":"2024-10-15T17:16:17.733198Z","shell.execute_reply":"2024-10-15T17:16:18.576688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:16:18.579161Z","iopub.execute_input":"2024-10-15T17:16:18.579575Z","iopub.status.idle":"2024-10-15T17:16:19.981702Z","shell.execute_reply.started":"2024-10-15T17:16:18.579530Z","shell.execute_reply":"2024-10-15T17:16:19.980161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:16:19.983852Z","iopub.execute_input":"2024-10-15T17:16:19.984408Z","iopub.status.idle":"2024-10-15T17:16:20.642911Z","shell.execute_reply.started":"2024-10-15T17:16:19.984348Z","shell.execute_reply":"2024-10-15T17:16:20.641979Z"},"trusted":true},"execution_count":null,"outputs":[]}]}