{"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":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"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-16T04:25:29.965483Z","iopub.execute_input":"2024-10-16T04:25:29.965925Z","iopub.status.idle":"2024-10-16T04:25:45.798304Z","shell.execute_reply.started":"2024-10-16T04:25:29.965883Z","shell.execute_reply":"2024-10-16T04:25:45.797317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Load Data**","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-16T04:25:45.800069Z","iopub.execute_input":"2024-10-16T04:25:45.800657Z","iopub.status.idle":"2024-10-16T04:25:45.805752Z","shell.execute_reply.started":"2024-10-16T04:25:45.800616Z","shell.execute_reply":"2024-10-16T04:25:45.804600Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Data Visualisation**","metadata":{}},{"cell_type":"code","source":"def plot(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(('.jpg'))]\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-16T04:25:45.806913Z","iopub.execute_input":"2024-10-16T04:25:45.807351Z","iopub.status.idle":"2024-10-16T04:25:45.821294Z","shell.execute_reply.started":"2024-10-16T04:25:45.807312Z","shell.execute_reply":"2024-10-16T04:25:45.820232Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Visualization of train data\nplot(zip_train_path, num_images=10)","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:25:45.823590Z","iopub.execute_input":"2024-10-16T04:25:45.824316Z","iopub.status.idle":"2024-10-16T04:25:46.652237Z","shell.execute_reply.started":"2024-10-16T04:25:45.824263Z","shell.execute_reply":"2024-10-16T04:25:46.650974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Visualization of test data\nplot(zip_test_path, num_images=10)","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:25:46.653690Z","iopub.execute_input":"2024-10-16T04:25:46.654164Z","iopub.status.idle":"2024-10-16T04:25:47.344834Z","shell.execute_reply.started":"2024-10-16T04:25:46.654106Z","shell.execute_reply":"2024-10-16T04:25:47.343368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\nimport os\npath = \"/kaggle/input/dogs-vs-cats\"\nfor zip_file in os.listdir(path)[:2]:\n    zipfile.ZipFile(f\"{path}/{zip_file}\", 'r').extractall(\".\")\n#     print(f\"{path}/{zip_file}\")\n    print(f\"{zip_file} unzipped\")","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:25:47.346656Z","iopub.execute_input":"2024-10-16T04:25:47.347448Z","iopub.status.idle":"2024-10-16T04:26:02.786710Z","shell.execute_reply.started":"2024-10-16T04:25:47.347394Z","shell.execute_reply":"2024-10-16T04:26:02.785368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pd\ntrain_images = os.listdir(\"/kaggle/working/train\")\nCATEGORIES = []\n\nfor image_name in train_images:\n    class_name = image_name.split('.')[0]  # cat.588.jpg\n    CATEGORIES.append(0 if class_name=='cat' else 1)\n\ndf = pd.DataFrame({\"train_images\": train_images, \"CATEGORIES\": CATEGORIES})","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:26:02.788321Z","iopub.execute_input":"2024-10-16T04:26:02.788688Z","iopub.status.idle":"2024-10-16T04:26:02.830123Z","shell.execute_reply.started":"2024-10-16T04:26:02.788650Z","shell.execute_reply":"2024-10-16T04:26:02.829154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:26:02.831634Z","iopub.execute_input":"2024-10-16T04:26:02.832108Z","iopub.status.idle":"2024-10-16T04:26:02.851808Z","shell.execute_reply.started":"2024-10-16T04:26:02.832051Z","shell.execute_reply":"2024-10-16T04:26:02.850797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[\"CATEGORIES\"].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:26:02.853036Z","iopub.execute_input":"2024-10-16T04:26:02.853382Z","iopub.status.idle":"2024-10-16T04:26:02.866297Z","shell.execute_reply.started":"2024-10-16T04:26:02.853347Z","shell.execute_reply":"2024-10-16T04:26:02.865185Z"},"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-16T04:26:02.869985Z","iopub.execute_input":"2024-10-16T04:26:02.871082Z","iopub.status.idle":"2024-10-16T04:26:02.879748Z","shell.execute_reply.started":"2024-10-16T04:26:02.871028Z","shell.execute_reply":"2024-10-16T04:26:02.878607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = preprocess(zip_train_path, new_size)\ntrain_dataset","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:26:02.881042Z","iopub.execute_input":"2024-10-16T04:26:02.881361Z","iopub.status.idle":"2024-10-16T04:27:08.185048Z","shell.execute_reply.started":"2024-10-16T04:26:02.881329Z","shell.execute_reply":"2024-10-16T04:27:08.183868Z"},"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-16T04:27:08.186411Z","iopub.execute_input":"2024-10-16T04:27:08.186833Z","iopub.status.idle":"2024-10-16T04:27:39.145990Z","shell.execute_reply.started":"2024-10-16T04:27:08.186794Z","shell.execute_reply":"2024-10-16T04:27:39.144865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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-16T04:27:39.147881Z","iopub.execute_input":"2024-10-16T04:27:39.148254Z","iopub.status.idle":"2024-10-16T04:27:39.154821Z","shell.execute_reply.started":"2024-10-16T04:27:39.148218Z","shell.execute_reply":"2024-10-16T04:27:39.153625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels = extract_tags(zip_train_path)","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:27:39.156236Z","iopub.execute_input":"2024-10-16T04:27:39.156673Z","iopub.status.idle":"2024-10-16T04:27:39.397733Z","shell.execute_reply.started":"2024-10-16T04:27:39.156627Z","shell.execute_reply":"2024-10-16T04:27:39.396640Z"},"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-16T04:27:39.399099Z","iopub.execute_input":"2024-10-16T04:27:39.399461Z","iopub.status.idle":"2024-10-16T04:27:39.405434Z","shell.execute_reply.started":"2024-10-16T04:27:39.399427Z","shell.execute_reply":"2024-10-16T04:27:39.404196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_binary = np.array([1 if label == 'dog' else 0 for label, _ in train_labels])\ntrain_dataset = np.expand_dims(train_dataset, axis=-1)","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:27:39.406997Z","iopub.execute_input":"2024-10-16T04:27:39.407559Z","iopub.status.idle":"2024-10-16T04:27:39.421135Z","shell.execute_reply.started":"2024-10-16T04:27:39.407513Z","shell.execute_reply":"2024-10-16T04:27:39.420026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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-16T04:27:39.422535Z","iopub.execute_input":"2024-10-16T04:27:39.423571Z","iopub.status.idle":"2024-10-16T04:27:40.820216Z","shell.execute_reply.started":"2024-10-16T04:27:39.423529Z","shell.execute_reply":"2024-10-16T04:27:40.819098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential([\n    Conv2D(16, (3, 3), activation='relu', input_shape=(128, 128, 1)),\n    MaxPooling2D((2, 2)),\n    Conv2D(32, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dropout(0.5),\n    Dense(1, activation='sigmoid')\n])\n\n# Compile the model\nmodel.compile(optimizer=\"adam\", loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:27:40.821529Z","iopub.execute_input":"2024-10-16T04:27:40.821901Z","iopub.status.idle":"2024-10-16T04:27:40.965317Z","shell.execute_reply.started":"2024-10-16T04:27:40.821864Z","shell.execute_reply":"2024-10-16T04:27:40.964110Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow import keras\nkeras.utils.plot_model(model,show_layer_activations=True,show_layer_names=True,show_shapes=True,show_dtype=True,to_file='model.png')","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:27:40.966651Z","iopub.execute_input":"2024-10-16T04:27:40.967027Z","iopub.status.idle":"2024-10-16T04:27:41.712171Z","shell.execute_reply.started":"2024-10-16T04:27:40.966990Z","shell.execute_reply":"2024-10-16T04:27:41.711022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train, y_train, epochs=10, validation_data=(X_val, y_val))","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:27:41.713513Z","iopub.execute_input":"2024-10-16T04:27:41.713893Z","iopub.status.idle":"2024-10-16T04:49:41.066228Z","shell.execute_reply.started":"2024-10-16T04:27:41.713856Z","shell.execute_reply":"2024-10-16T04:49:41.064410Z"},"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-16T04:49:41.069262Z","iopub.execute_input":"2024-10-16T04:49:41.069949Z","iopub.status.idle":"2024-10-16T04:49:41.679391Z","shell.execute_reply.started":"2024-10-16T04:49:41.069886Z","shell.execute_reply":"2024-10-16T04:49:41.678190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Evaluating on test data...\")\nloss, accuracy = model.evaluate(X_test, y_test)\nprint(f'Accuracy: {accuracy:.4f}')\nprint(f'Loss: {loss:.4f}')","metadata":{"execution":{"iopub.status.busy":"2024-10-16T04:49:41.680648Z","iopub.execute_input":"2024-10-16T04:49:41.680992Z","iopub.status.idle":"2024-10-16T04:49:47.230430Z","shell.execute_reply.started":"2024-10-16T04:49:41.680958Z","shell.execute_reply":"2024-10-16T04:49:47.229100Z"},"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-16T04:49:47.231760Z","iopub.execute_input":"2024-10-16T04:49:47.232138Z","iopub.status.idle":"2024-10-16T04:49:52.553099Z","shell.execute_reply.started":"2024-10-16T04:49:47.232095Z","shell.execute_reply":"2024-10-16T04:49:52.551832Z"},"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-16T04:49:52.554568Z","iopub.execute_input":"2024-10-16T04:49:52.554951Z","iopub.status.idle":"2024-10-16T04:49:53.241007Z","shell.execute_reply.started":"2024-10-16T04:49:52.554912Z","shell.execute_reply":"2024-10-16T04:49:53.239935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}