{"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-09-24T09:54:09.978884Z","iopub.execute_input":"2024-09-24T09:54:09.979255Z","iopub.status.idle":"2024-09-24T09:54:10.278281Z","shell.execute_reply.started":"2024-09-24T09:54:09.979215Z","shell.execute_reply":"2024-09-24T09:54:10.277444Z"},"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-09-24T09:36:58.182476Z","iopub.execute_input":"2024-09-24T09:36:58.182993Z","iopub.status.idle":"2024-09-24T09:36:58.186875Z","shell.execute_reply.started":"2024-09-24T09:36:58.182959Z","shell.execute_reply":"2024-09-24T09:36:58.186007Z"},"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-09-24T09:36:58.187801Z","iopub.execute_input":"2024-09-24T09:36:58.188074Z","iopub.status.idle":"2024-09-24T09:36:58.213745Z","shell.execute_reply.started":"2024-09-24T09:36:58.188043Z","shell.execute_reply":"2024-09-24T09:36:58.212864Z"},"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-09-24T09:36:58.215851Z","iopub.execute_input":"2024-09-24T09:36:58.216600Z","iopub.status.idle":"2024-09-24T09:36:59.043467Z","shell.execute_reply.started":"2024-09-24T09:36:58.216567Z","shell.execute_reply":"2024-09-24T09:36:59.042601Z"},"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-09-24T09:36:59.044580Z","iopub.execute_input":"2024-09-24T09:36:59.044849Z","iopub.status.idle":"2024-09-24T09:36:59.737174Z","shell.execute_reply.started":"2024-09-24T09:36:59.044820Z","shell.execute_reply":"2024-09-24T09:36:59.736228Z"},"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-09-24T09:36:59.738253Z","iopub.execute_input":"2024-09-24T09:36:59.738605Z","iopub.status.idle":"2024-09-24T09:36:59.742793Z","shell.execute_reply.started":"2024-09-24T09:36:59.738570Z","shell.execute_reply":"2024-09-24T09:36:59.741884Z"},"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-09-24T09:36:59.744057Z","iopub.execute_input":"2024-09-24T09:36:59.744811Z","iopub.status.idle":"2024-09-24T09:36:59.754190Z","shell.execute_reply.started":"2024-09-24T09:36:59.744768Z","shell.execute_reply":"2024-09-24T09:36:59.753395Z"},"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-09-24T09:36:59.755319Z","iopub.execute_input":"2024-09-24T09:36:59.755645Z","iopub.status.idle":"2024-09-24T09:37:00.569653Z","shell.execute_reply.started":"2024-09-24T09:36:59.755614Z","shell.execute_reply":"2024-09-24T09:37:00.568267Z"},"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-09-24T09:37:00.571759Z","iopub.execute_input":"2024-09-24T09:37:00.572254Z","iopub.status.idle":"2024-09-24T09:37:01.073669Z","shell.execute_reply.started":"2024-09-24T09:37:00.572197Z","shell.execute_reply":"2024-09-24T09:37:01.072178Z"},"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-09-24T09:37:01.077965Z","iopub.execute_input":"2024-09-24T09:37:01.078803Z","iopub.status.idle":"2024-09-24T09:37:01.086515Z","shell.execute_reply.started":"2024-09-24T09:37:01.078730Z","shell.execute_reply":"2024-09-24T09:37:01.085330Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count(zip_train_path)","metadata":{"execution":{"iopub.status.busy":"2024-09-24T09:37:01.088088Z","iopub.execute_input":"2024-09-24T09:37:01.089187Z","iopub.status.idle":"2024-09-24T09:37:01.419393Z","shell.execute_reply.started":"2024-09-24T09:37:01.089138Z","shell.execute_reply":"2024-09-24T09:37:01.418365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count(zip_test_path)","metadata":{"execution":{"iopub.status.busy":"2024-09-24T09:37:01.420539Z","iopub.execute_input":"2024-09-24T09:37:01.420902Z","iopub.status.idle":"2024-09-24T09:37:01.567174Z","shell.execute_reply.started":"2024-09-24T09:37:01.420859Z","shell.execute_reply":"2024-09-24T09:37:01.566088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Preprocess images by converting to grayscale and resizing","metadata":{"execution":{"iopub.status.busy":"2024-09-24T09:37:01.568586Z","iopub.execute_input":"2024-09-24T09:37:01.568992Z","iopub.status.idle":"2024-09-24T09:37:01.573366Z","shell.execute_reply.started":"2024-09-24T09:37:01.568946Z","shell.execute_reply":"2024-09-24T09:37:01.572329Z"},"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-09-24T09:37:01.574633Z","iopub.execute_input":"2024-09-24T09:37:01.574963Z","iopub.status.idle":"2024-09-24T09:37:01.583418Z","shell.execute_reply.started":"2024-09-24T09:37:01.574923Z","shell.execute_reply":"2024-09-24T09:37:01.582500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = preprocess(zip_train_path, new_size)","metadata":{"execution":{"iopub.status.busy":"2024-09-24T09:37:01.584666Z","iopub.execute_input":"2024-09-24T09:37:01.585018Z","iopub.status.idle":"2024-09-24T09:38:01.906632Z","shell.execute_reply.started":"2024-09-24T09:37:01.584977Z","shell.execute_reply":"2024-09-24T09:38:01.905795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dataset = preprocess(zip_test_path, new_size)","metadata":{"execution":{"iopub.status.busy":"2024-09-24T09:38:01.907770Z","iopub.execute_input":"2024-09-24T09:38:01.908082Z","iopub.status.idle":"2024-09-24T09:38:31.028046Z","shell.execute_reply.started":"2024-09-24T09:38:01.908050Z","shell.execute_reply":"2024-09-24T09:38:31.027159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset","metadata":{"execution":{"iopub.status.busy":"2024-09-24T09:38:31.029132Z","iopub.execute_input":"2024-09-24T09:38:31.029448Z","iopub.status.idle":"2024-09-24T09:38:31.038856Z","shell.execute_reply.started":"2024-09-24T09:38:31.029404Z","shell.execute_reply":"2024-09-24T09:38:31.037888Z"},"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-09-24T09:38:31.039866Z","iopub.execute_input":"2024-09-24T09:38:31.040185Z","iopub.status.idle":"2024-09-24T09:38:31.048725Z","shell.execute_reply.started":"2024-09-24T09:38:31.040151Z","shell.execute_reply":"2024-09-24T09:38:31.047950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels = extract_tags(zip_train_path)","metadata":{"execution":{"iopub.status.busy":"2024-09-24T09:38:31.049814Z","iopub.execute_input":"2024-09-24T09:38:31.050158Z","iopub.status.idle":"2024-09-24T09:38:31.547088Z","shell.execute_reply.started":"2024-09-24T09:38:31.050116Z","shell.execute_reply":"2024-09-24T09:38:31.546137Z"},"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-09-24T09:38:59.323891Z","iopub.execute_input":"2024-09-24T09:38:59.324280Z","iopub.status.idle":"2024-09-24T09:38:59.329832Z","shell.execute_reply.started":"2024-09-24T09:38:59.324243Z","shell.execute_reply":"2024-09-24T09:38:59.328854Z"},"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-09-24T09:47:18.268237Z","iopub.execute_input":"2024-09-24T09:47:18.269133Z","iopub.status.idle":"2024-09-24T09:47:19.397121Z","shell.execute_reply.started":"2024-09-24T09:47:18.269091Z","shell.execute_reply":"2024-09-24T09:47:19.396034Z"},"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-09-24T09:47:21.619207Z","iopub.execute_input":"2024-09-24T09:47:21.620257Z","iopub.status.idle":"2024-09-24T09:47:21.945035Z","shell.execute_reply.started":"2024-09-24T09:47:21.620217Z","shell.execute_reply":"2024-09-24T09:47:21.944247Z"},"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-09-24T09:47:24.188306Z","iopub.execute_input":"2024-09-24T09:47:24.188710Z","iopub.status.idle":"2024-09-24T09:47:24.198126Z","shell.execute_reply.started":"2024-09-24T09:47:24.188671Z","shell.execute_reply":"2024-09-24T09:47:24.197245Z"},"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-09-24T09:47:26.348896Z","iopub.execute_input":"2024-09-24T09:47:26.349740Z","iopub.status.idle":"2024-09-24T09:49:03.044685Z","shell.execute_reply.started":"2024-09-24T09:47:26.349700Z","shell.execute_reply":"2024-09-24T09:49:03.043618Z"},"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-09-24T09:49:07.078342Z","iopub.execute_input":"2024-09-24T09:49:07.079225Z","iopub.status.idle":"2024-09-24T09:49:07.723883Z","shell.execute_reply.started":"2024-09-24T09:49:07.079187Z","shell.execute_reply":"2024-09-24T09:49:07.722966Z"},"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-09-24T09:49:17.854633Z","iopub.execute_input":"2024-09-24T09:49:17.855493Z","iopub.status.idle":"2024-09-24T09:49:18.511872Z","shell.execute_reply.started":"2024-09-24T09:49:17.855440Z","shell.execute_reply":"2024-09-24T09:49:18.510985Z"},"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-09-24T09:50:30.183556Z","iopub.execute_input":"2024-09-24T09:50:30.183937Z","iopub.status.idle":"2024-09-24T09:50:30.836481Z","shell.execute_reply.started":"2024-09-24T09:50:30.183899Z","shell.execute_reply":"2024-09-24T09:50:30.835589Z"},"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-09-24T09:54:14.533285Z","iopub.execute_input":"2024-09-24T09:54:14.534464Z","iopub.status.idle":"2024-09-24T09:54:15.197473Z","shell.execute_reply.started":"2024-09-24T09:54:14.534403Z","shell.execute_reply":"2024-09-24T09:54:15.196483Z"},"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-09-24T09:57:21.207493Z","iopub.execute_input":"2024-09-24T09:57:21.208323Z","iopub.status.idle":"2024-09-24T09:57:21.818369Z","shell.execute_reply.started":"2024-09-24T09:57:21.208258Z","shell.execute_reply":"2024-09-24T09:57:21.817438Z"},"trusted":true},"execution_count":null,"outputs":[]}]}