{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/CristianCruz0309/Curso_Fundamentos_IA_Machine_Learning/blob/main/fundamentos_ia.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "o1NsPEpBa4ud"
      },
      "source": [
        "# **Clase 1**\n",
        "\n",
        "## Aprendizaje Supervisado - Clasificación"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VT6cbjCTZ8_5",
        "outputId": "e5fa79f3-4d5a-42cb-8011-0ed9abfa540e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Exactitud del modelo: 100.00%\n"
          ]
        }
      ],
      "source": [
        "# Paso 1: Importar las bibliotecas necesarias\n",
        "from sklearn.datasets import load_iris\n",
        "from sklearn.model_selection import train_test_split\n",
        "from sklearn.tree import DecisionTreeClassifier\n",
        "from sklearn.metrics import accuracy_score\n",
        "\n",
        "# Paso 2: Cargar el dataset Iris\n",
        "iris = load_iris()\n",
        "X = iris.data   # Caracteristicas (largo y ancho de pétalos y sépalos)\n",
        "y = iris.target # Rótulos (especies de flores)\n",
        "\n",
        "# Paso 3: Dividir los datos para entrenamiento y para prueba\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
        "\n",
        "# Paso 4: Entrenar el modelo\n",
        "model = DecisionTreeClassifier()\n",
        "model.fit(X_train, y_train)\n",
        "\n",
        "# Paso 5: Realizar previsiones y evaluar el modelo\n",
        "y_pred = model.predict(X_test)\n",
        "accuracy = accuracy_score(y_test, y_pred)\n",
        "print(f\"Exactitud del modelo: {accuracy * 100:.2f}%\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "y25Wl-P7bMjB",
        "outputId": "39de1b89-d629-4910-a599-bdb2b3a06133"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Exactitud del modelo de Árbol de Decisión: 100.00%\n",
            "Exactitud del modelo KNN: 100.00%\n"
          ]
        }
      ],
      "source": [
        "# Paso 1: Importar las bibliotecas necesarias\n",
        "from sklearn.tree import DecisionTreeClassifier\n",
        "from sklearn.neighbors import KNeighborsClassifier\n",
        "from sklearn.model_selection import train_test_split\n",
        "from sklearn.metrics import accuracy_score\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "from sklearn.datasets import load_iris\n",
        "import pandas as pd\n",
        "\n",
        "# Paso 2: Cargar y preparar el dataset Iris\n",
        "dataset = load_iris()\n",
        "df = pd.DataFrame(dataset.data, columns=dataset.feature_names)\n",
        "df['species'] = dataset.target\n",
        "\n",
        "# Paso 3: Normalizar los datos\n",
        "scaler = StandardScaler()\n",
        "X_scaled = scaler.fit_transform(df.drop(columns=['species']))\n",
        "\n",
        "# Paso 4: Dividir los datos en entrenamiento y prueba\n",
        "X_train, X_test, y_train, y_test = train_test_split(X_scaled, df['species'], test_size=0.3, random_state=42)\n",
        "\n",
        "# Paso 5: Entrenar y evaluar el árbol de decisión\n",
        "tree_model = DecisionTreeClassifier()\n",
        "tree_model.fit(X_train, y_train)\n",
        "tree_accuracy = accuracy_score(y_test, tree_model.predict(X_test))\n",
        "print(f\"Exactitud del modelo de Árbol de Decisión: {tree_accuracy * 100:.2f}%\")\n",
        "\n",
        "# Paso 6: Entrenar y evaluar el KNN\n",
        "knn_model = KNeighborsClassifier()\n",
        "knn_model.fit(X_train, y_train)\n",
        "knn_accuracy = accuracy_score(y_test, knn_model.predict(X_test))\n",
        "print(f\"Exactitud del modelo KNN: {knn_accuracy * 100:.2f}%\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "j-gTcWAkgMKQ"
      },
      "source": [
        "## Aprendizaje Supervisado - Regresión"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 736
        },
        "id": "HTqkVk2kgXIW",
        "outputId": "4ab66cd9-5133-49cf-8f63-5cae438aec73"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Coeficiente angular (b1): 19.43\n",
            "Intercepto (b0): 514.29\n",
            "\n",
            "Métricas de Evaluación:\n",
            "R² en datos de prueba: 0.94\n",
            "Erro Medio Absoluto (MAE): 7.39\n",
            "Raíz del Error Cuadrático Medio (RMSE): 9.34\n",
            "\n",
            "Promedio de los puntajes de la validación cruzada: 0.95\n"
          ]
        },
        {
          "data": {
            "image/png": "[encoded data, 46820 characters]\n",
            "text/plain": [
              "<Figure size 800x600 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "# Importando bibliotecas\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "from sklearn.linear_model import LinearRegression\n",
        "from sklearn.model_selection import train_test_split, cross_val_score\n",
        "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
        "\n",
        "# Creando un conjunto de datos simulados\n",
        "np.random.seed(42)\n",
        "X = 2.5 * np.random.randn(100, 1) + 25  # Tamaño del inmueble (m2)\n",
        "y = 500 + (X * 20) + np.random.randn(100, 1) * 10  # Precio del inmueble (miles de dólares)\n",
        "\n",
        "# Definiendo features (independientes) y labels (dependientes)\n",
        "features = X\n",
        "labels = y\n",
        "\n",
        "# Dividiendo los datos en entrenamiento y prueba\n",
        "X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)\n",
        "\n",
        "# Creando y entrenando el modelo\n",
        "model = LinearRegression()\n",
        "model.fit(X_train, y_train)\n",
        "\n",
        "#Modelo de Regresión lineal\n",
        "# Y = A X + B\n",
        "# Y -> Variable de salida\n",
        "# X -> Tamaño del inmueble\n",
        "# A y B son los coeficientes\n",
        "\n",
        "# Coeficientes de Regresión\n",
        "print(f\"Coeficiente angular (b1): {model.coef_[0][0]:.2f}\")\n",
        "print(f\"Intercepto (b0): {model.intercept_[0]:.2f}\")\n",
        "\n",
        "# Predicciones con los datos de prueba\n",
        "y_pred = model.predict(X_test)\n",
        "\n",
        "# Indicadores de la Evaluación del modelo con los datos de prueba\n",
        "#R² Ajuste de los datos al modelo\n",
        "r2 = r2_score(y_test, y_pred)\n",
        "#MAE (Error Medio Absoluto)\n",
        "mae = mean_absolute_error(y_test, y_pred)\n",
        "#RMSE (Raíz del error Cuadrático Medio)\n",
        "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n",
        "\n",
        "print(f\"\\nMétricas de Evaluación:\")\n",
        "print(f\"R² en datos de prueba: {r2:.2f}\")\n",
        "print(f\"Erro Medio Absoluto (MAE): {mae:.2f}\")\n",
        "print(f\"Raíz del Error Cuadrático Medio (RMSE): {rmse:.2f}\")\n",
        "\n",
        "# Evaluación cruzada\n",
        "cv_scores = cross_val_score(model, features, labels, cv=5, scoring='r2')\n",
        "print(f\"\\nPromedio de los puntajes de la validación cruzada: {cv_scores.mean():.2f}\")\n",
        "\n",
        "# Gráfico de la recta de Regresión\n",
        "plt.figure(figsize=(8, 6))\n",
        "plt.scatter(X_test, y_test, color='blue', label='Datos reales')\n",
        "plt.plot(X_test, y_pred, color='red', linewidth=2, label='Regresión Lineal')\n",
        "plt.xlabel(\"Tamaño del Inmueble\")\n",
        "plt.ylabel(\"Precio del Inmueble\")\n",
        "plt.title(\"Regresión Lineal: Precio x Tamaño del Inmueble\")\n",
        "plt.legend()\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LRndTZuznABT"
      },
      "source": [
        "# **Actividad - Clase 1**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "MJ74jCXInKMv",
        "outputId": "d6ba1a2d-8f4b-4891-fdbe-2462558bec9b"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Precisión del modelo: 1.00\n",
            "Precisión media en la validación cruzada: 0.95\n",
            "Clase prevista para la nueva muestra: setosa\n"
          ]
        },
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "/usr/local/lib/python3.12/dist-packages/sklearn/utils/validation.py:2739: UserWarning: X does not have valid feature names, but DecisionTreeClassifier was fitted with feature names\n",
            "  warnings.warn(\n"
          ]
        }
      ],
      "source": [
        "import numpy as np\n",
        "import pandas as pd\n",
        "from sklearn import datasets\n",
        "from sklearn.model_selection import train_test_split, cross_val_score\n",
        "from sklearn.tree import DecisionTreeClassifier\n",
        "from sklearn.metrics import accuracy_score\n",
        "\n",
        "# Cargar el dataset Iris de la biblioteca sklearn\n",
        "dataset = datasets.load_iris()\n",
        "\n",
        "# Convertir a DataFrame de Pandas para facilitar la manipulación de los datos\n",
        "df = pd.DataFrame(data=dataset.data, columns=dataset.feature_names)\n",
        "df['target'] = dataset.target  # Agregar la columna con las clases de las flores\n",
        "\n",
        "# Separar los atributos (X) y las etiquetas (y)\n",
        "X = df.iloc[:, :-1]  # Todas las columnas excepto la última\n",
        "y = df['target']  # Última columna, que contiene las clases\n",
        "\n",
        "# Dividir los datos en conjunto de entrenamiento y prueba (80% entrenamiento, 20% prueba)\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
        "\n",
        "# Crear y entrenar un modelo de Árbol de Decisión\n",
        "model = DecisionTreeClassifier(random_state=42)\n",
        "model.fit(X_train, y_train)\n",
        "\n",
        "# Hacer predicciones en los datos de prueba\n",
        "y_pred = model.predict(X_test)\n",
        "\n",
        "# Evaluar el rendimiento del modelo\n",
        "accuracy = accuracy_score(y_test, y_pred)\n",
        "print(f'Precisión del modelo: {accuracy:.2f}')\n",
        "\n",
        "# Aplicar validación cruzada para mejor evaluación del rendimiento\n",
        "cross_val_scores = cross_val_score(model, X, y, cv=5)\n",
        "print(f'Precisión media en la validación cruzada: {cross_val_scores.mean():.2f}')\n",
        "\n",
        "# Probar con una nueva muestra\n",
        "nueva_muestra = np.array([[5.1, 3.5, 1.4, 0.2]])  # Ejemplo de medidas de una flor\n",
        "prediccion = model.predict(nueva_muestra)\n",
        "print(f'Clase prevista para la nueva muestra: {dataset.target_names[prediccion[0]]}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5jAzFN36nfL8"
      },
      "source": [
        "# **Clase 2**\n",
        "\n",
        "## Ejemplos de Clasificación y Regresión"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 226
        },
        "id": "4tp9L9dHnpL7",
        "outputId": "b0503600-f525-41a6-b4af-3b84810e237b"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "summary": "{\n  \"name\": \"df\",\n  \"rows\": 20640,\n  \"fields\": [\n    {\n      \"column\": \"MedInc\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 1.8998217179452732,\n        \"min\": 0.4999,\n        \"max\": 15.0001,\n        \"num_unique_values\": 12928,\n        \"samples\": [\n          5.0286,\n          2.0433,\n          6.1228\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"HouseAge\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 12.585557612111637,\n        \"min\": 1.0,\n        \"max\": 52.0,\n        \"num_unique_values\": 52,\n        \"samples\": [\n          35.0,\n          25.0,\n          7.0\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"AveRooms\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 2.4741731394243205,\n        \"min\": 0.8461538461538461,\n        \"max\": 141.9090909090909,\n        \"num_unique_values\": 19392,\n        \"samples\": [\n          6.111269614835948,\n          5.912820512820513,\n          5.7924528301886795\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"AveBedrms\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.47391085679546435,\n        \"min\": 0.3333333333333333,\n        \"max\": 34.06666666666667,\n        \"num_unique_values\": 14233,\n        \"samples\": [\n          0.9906542056074766,\n          1.112099644128114,\n          1.0398230088495575\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"Population\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 1132.4621217653375,\n        \"min\": 3.0,\n        \"max\": 35682.0,\n        \"num_unique_values\": 3888,\n        \"samples\": [\n          4169.0,\n          636.0,\n          3367.0\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"AveOccup\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 10.386049562213591,\n        \"min\": 0.6923076923076923,\n        \"max\": 1243.3333333333333,\n        \"num_unique_values\": 18841,\n        \"samples\": [\n          2.6939799331103678,\n          3.559375,\n          3.297082228116711\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"Latitude\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 2.1359523974571117,\n        \"min\": 32.54,\n        \"max\": 41.95,\n        \"num_unique_values\": 862,\n        \"samples\": [\n          33.7,\n          34.41,\n          38.24\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"Longitude\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 2.003531723502581,\n        \"min\": -124.35,\n        \"max\": -114.31,\n        \"num_unique_values\": 844,\n        \"samples\": [\n          -118.63,\n          -119.86,\n          -121.26\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"PRICE\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 1.1539561587441483,\n        \"min\": 0.14999,\n        \"max\": 5.00001,\n        \"num_unique_values\": 3842,\n        \"samples\": [\n          1.943,\n          3.79,\n          2.301\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    }\n  ]\n}",
              "type": "dataframe",
              "variable_name": "df"
            },
            "text/html": [
              "\n",
              "  <div id=\"df-4c430331-c369-4874-9656-e2c2b4d44bd4\" class=\"colab-df-container\">\n",
              "    <div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>MedInc</th>\n",
              "      <th>HouseAge</th>\n",
              "      <th>AveRooms</th>\n",
              "      <th>AveBedrms</th>\n",
              "      <th>Population</th>\n",
              "      <th>AveOccup</th>\n",
              "      <th>Latitude</th>\n",
              "      <th>Longitude</th>\n",
              "      <th>PRICE</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>8.3252</td>\n",
              "      <td>41.0</td>\n",
              "      <td>6.984127</td>\n",
              "      <td>1.023810</td>\n",
              "      <td>322.0</td>\n",
              "      <td>2.555556</td>\n",
              "      <td>37.88</td>\n",
              "      <td>-122.23</td>\n",
              "      <td>4.526</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>8.3014</td>\n",
              "      <td>21.0</td>\n",
              "      <td>6.238137</td>\n",
              "      <td>0.971880</td>\n",
              "      <td>2401.0</td>\n",
              "      <td>2.109842</td>\n",
              "      <td>37.86</td>\n",
              "      <td>-122.22</td>\n",
              "      <td>3.585</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>7.2574</td>\n",
              "      <td>52.0</td>\n",
              "      <td>8.288136</td>\n",
              "      <td>1.073446</td>\n",
              "      <td>496.0</td>\n",
              "      <td>2.802260</td>\n",
              "      <td>37.85</td>\n",
              "      <td>-122.24</td>\n",
              "      <td>3.521</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>5.6431</td>\n",
              "      <td>52.0</td>\n",
              "      <td>5.817352</td>\n",
              "      <td>1.073059</td>\n",
              "      <td>558.0</td>\n",
              "      <td>2.547945</td>\n",
              "      <td>37.85</td>\n",
              "      <td>-122.25</td>\n",
              "      <td>3.413</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>3.8462</td>\n",
              "      <td>52.0</td>\n",
              "      <td>6.281853</td>\n",
              "      <td>1.081081</td>\n",
              "      <td>565.0</td>\n",
              "      <td>2.181467</td>\n",
              "      <td>37.85</td>\n",
              "      <td>-122.25</td>\n",
              "      <td>3.422</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>\n",
              "    <div class=\"colab-df-buttons\">\n",
              "\n",
              "  <div class=\"colab-df-container\">\n",
              "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-4c430331-c369-4874-9656-e2c2b4d44bd4')\"\n",
              "            title=\"Convert this dataframe to an interactive table.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
              "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "\n",
              "  <style>\n",
              "    .colab-df-container {\n",
              "      display:flex;\n",
              "      gap: 12px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert {\n",
              "      background-color: #E8F0FE;\n",
              "      border: none;\n",
              "      border-radius: 50%;\n",
              "      cursor: pointer;\n",
              "      display: none;\n",
              "      fill: #1967D2;\n",
              "      height: 32px;\n",
              "      padding: 0 0 0 0;\n",
              "      width: 32px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert:hover {\n",
              "      background-color: #E2EBFA;\n",
              "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "      fill: #174EA6;\n",
              "    }\n",
              "\n",
              "    .colab-df-buttons div {\n",
              "      margin-bottom: 4px;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert {\n",
              "      background-color: #3B4455;\n",
              "      fill: #D2E3FC;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert:hover {\n",
              "      background-color: #434B5C;\n",
              "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "      fill: #FFFFFF;\n",
              "    }\n",
              "  </style>\n",
              "\n",
              "    <script>\n",
              "      const buttonEl =\n",
              "        document.querySelector('#df-4c430331-c369-4874-9656-e2c2b4d44bd4 button.colab-df-convert');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      async function convertToInteractive(key) {\n",
              "        const element = document.querySelector('#df-4c430331-c369-4874-9656-e2c2b4d44bd4');\n",
              "        const dataTable =\n",
              "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
              "                                                    [key], {});\n",
              "        if (!dataTable) return;\n",
              "\n",
              "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
              "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
              "          + ' to learn more about interactive tables.';\n",
              "        element.innerHTML = '';\n",
              "        dataTable['output_type'] = 'display_data';\n",
              "        await google.colab.output.renderOutput(dataTable, element);\n",
              "        const docLink = document.createElement('div');\n",
              "        docLink.innerHTML = docLinkHtml;\n",
              "        element.appendChild(docLink);\n",
              "      }\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "\n",
              "    </div>\n",
              "  </div>\n"
            ],
            "text/plain": [
              "   MedInc  HouseAge  AveRooms  AveBedrms  Population  AveOccup  Latitude  \\\n",
              "0  8.3252      41.0  6.984127   1.023810       322.0  2.555556     37.88   \n",
              "1  8.3014      21.0  6.238137   0.971880      2401.0  2.109842     37.86   \n",
              "2  7.2574      52.0  8.288136   1.073446       496.0  2.802260     37.85   \n",
              "3  5.6431      52.0  5.817352   1.073059       558.0  2.547945     37.85   \n",
              "4  3.8462      52.0  6.281853   1.081081       565.0  2.181467     37.85   \n",
              "\n",
              "   Longitude  PRICE  \n",
              "0    -122.23  4.526  \n",
              "1    -122.22  3.585  \n",
              "2    -122.24  3.521  \n",
              "3    -122.25  3.413  \n",
              "4    -122.25  3.422  "
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from sklearn.datasets import fetch_california_housing\n",
        "\n",
        "california = fetch_california_housing()\n",
        "df = pd.DataFrame(california.data, columns=california.feature_names)\n",
        "df['PRICE'] = california.target\n",
        "\n",
        "# Ver las primeras 5 filas de los datos\n",
        "df.head()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 531
        },
        "id": "-e69_ZAZo8QH",
        "outputId": "0eb34eb3-ea65-43ff-f80b-5ad607e90d5a"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Error Cuadrático Medio (MSE): 0.53\n",
            "Coeficiente de Determinación (R²): 0.60\n"
          ]
        },
        {
          "data": {
            "image/png": "[encoded data, 191396 characters]\n",
            "text/plain": [
              "<Figure size 1000x600 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "import numpy as np\n",
        "import pandas as pd\n",
        "import matplotlib.pyplot as plt\n",
        "import seaborn as sns\n",
        "from sklearn.linear_model import LinearRegression\n",
        "from sklearn.model_selection import train_test_split\n",
        "from sklearn.metrics import mean_squared_error, r2_score\n",
        "from sklearn.datasets import fetch_california_housing\n",
        "\n",
        "# Cargar el conjunto de datos\n",
        "california = fetch_california_housing()\n",
        "df = pd.DataFrame(california.data, columns=california.feature_names)\n",
        "df['PRICE'] = california.target\n",
        "\n",
        "# Dividir los datos en datos de entrenamiento y de prueba\n",
        "X = df.drop('PRICE', axis=1)\n",
        "y = df['PRICE']\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
        "\n",
        "# Entrenar el modelo\n",
        "model = LinearRegression()\n",
        "model.fit(X_train, y_train)\n",
        "\n",
        "# Realizar la prevision\n",
        "y_pred = model.predict(X_test)\n",
        "\n",
        "# Evaluar el modelo\n",
        "mse = mean_squared_error(y_test, y_pred)\n",
        "r2 = r2_score(y_test, y_pred)\n",
        "\n",
        "# Exhibir las métricas\n",
        "print(f'Error Cuadrático Medio (MSE): {mse:.2f}')\n",
        "print(f'Coeficiente de Determinación (R²): {r2:.2f}')\n",
        "\n",
        "# Visualización de los resultados\n",
        "plt.figure(figsize=(10, 6))\n",
        "sns.scatterplot(x=y_test, y=y_pred, alpha=0.6)\n",
        "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], '--r', linewidth=2) # Línea de referencia\n",
        "plt.xlabel(\"Valores Reales\")\n",
        "plt.ylabel(\"Valores Previstos\")\n",
        "plt.title(\"Regresión Lineal: Valores Reales vs. Previstos\")\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 226
        },
        "id": "jDuKdCemqg8a",
        "outputId": "692da19e-0258-4488-dfd8-104bfd2fdc48"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "summary": "{\n  \"name\": \"df\",\n  \"rows\": 442,\n  \"fields\": [\n    {\n      \"column\": \"age\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.0476190476190476,\n        \"min\": -0.1072256316073538,\n        \"max\": 0.11072667545381144,\n        \"num_unique_values\": 58,\n        \"samples\": [\n          0.038075906433423026,\n          -0.09269547780327612,\n          0.01991321417832592\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"sex\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.0476190476190478,\n        \"min\": -0.044641636506989144,\n        \"max\": 0.05068011873981862,\n        \"num_unique_values\": 2,\n        \"samples\": [\n          -0.044641636506989144,\n          0.05068011873981862\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"bmi\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.04761904761904761,\n        \"min\": -0.09027529589850945,\n        \"max\": 0.17055522598064407,\n        \"num_unique_values\": 163,\n        \"samples\": [\n          0.008883414898524095,\n          -0.05470749746044306\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"bp\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.04761904761904762,\n        \"min\": -0.11239880254408448,\n        \"max\": 0.13204361674121307,\n        \"num_unique_values\": 100,\n        \"samples\": [\n          0.03333707926361473,\n          0.02531523648988596\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"s1\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.047619047619047554,\n        \"min\": -0.12678066991651324,\n        \"max\": 0.15391371315651542,\n        \"num_unique_values\": 141,\n        \"samples\": [\n          0.041085578784023497,\n          0.08374011738825825\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"s2\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.047619047619047644,\n        \"min\": -0.11561306597939897,\n        \"max\": 0.19878798965729408,\n        \"num_unique_values\": 302,\n        \"samples\": [\n          0.07415490186505921,\n          0.07008397186179521\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"s3\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.04761904761904758,\n        \"min\": -0.10230705051741597,\n        \"max\": 0.18117906039727852,\n        \"num_unique_values\": 63,\n        \"samples\": [\n          0.09281975309919192,\n          0.15908923357275687\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"s4\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.047619047619047554,\n        \"min\": -0.0763945037500033,\n        \"max\": 0.18523444326019867,\n        \"num_unique_values\": 66,\n        \"samples\": [\n          0.08670845052151895,\n          -0.024732934523729287\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"s5\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.04761904761904763,\n        \"min\": -0.12609712083330468,\n        \"max\": 0.13359728192191356,\n        \"num_unique_values\": 184,\n        \"samples\": [\n          -0.07213275338232743,\n          -0.021395309255276825\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"s6\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.04761904761904766,\n        \"min\": -0.13776722569000302,\n        \"max\": 0.13561183068907107,\n        \"num_unique_values\": 56,\n        \"samples\": [\n          -0.01764612515980379,\n          -0.09634615654165846\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    }\n  ]\n}",
              "type": "dataframe",
              "variable_name": "df"
            },
            "text/html": [
              "\n",
              "  <div id=\"df-53aa6628-5b9f-4fce-b9e1-bd41f6c6a9a8\" class=\"colab-df-container\">\n",
              "    <div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>age</th>\n",
              "      <th>sex</th>\n",
              "      <th>bmi</th>\n",
              "      <th>bp</th>\n",
              "      <th>s1</th>\n",
              "      <th>s2</th>\n",
              "      <th>s3</th>\n",
              "      <th>s4</th>\n",
              "      <th>s5</th>\n",
              "      <th>s6</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>0.038076</td>\n",
              "      <td>0.050680</td>\n",
              "      <td>0.061696</td>\n",
              "      <td>0.021872</td>\n",
              "      <td>-0.044223</td>\n",
              "      <td>-0.034821</td>\n",
              "      <td>-0.043401</td>\n",
              "      <td>-0.002592</td>\n",
              "      <td>0.019907</td>\n",
              "      <td>-0.017646</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>-0.001882</td>\n",
              "      <td>-0.044642</td>\n",
              "      <td>-0.051474</td>\n",
              "      <td>-0.026328</td>\n",
              "      <td>-0.008449</td>\n",
              "      <td>-0.019163</td>\n",
              "      <td>0.074412</td>\n",
              "      <td>-0.039493</td>\n",
              "      <td>-0.068332</td>\n",
              "      <td>-0.092204</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>0.085299</td>\n",
              "      <td>0.050680</td>\n",
              "      <td>0.044451</td>\n",
              "      <td>-0.005670</td>\n",
              "      <td>-0.045599</td>\n",
              "      <td>-0.034194</td>\n",
              "      <td>-0.032356</td>\n",
              "      <td>-0.002592</td>\n",
              "      <td>0.002861</td>\n",
              "      <td>-0.025930</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>-0.089063</td>\n",
              "      <td>-0.044642</td>\n",
              "      <td>-0.011595</td>\n",
              "      <td>-0.036656</td>\n",
              "      <td>0.012191</td>\n",
              "      <td>0.024991</td>\n",
              "      <td>-0.036038</td>\n",
              "      <td>0.034309</td>\n",
              "      <td>0.022688</td>\n",
              "      <td>-0.009362</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>0.005383</td>\n",
              "      <td>-0.044642</td>\n",
              "      <td>-0.036385</td>\n",
              "      <td>0.021872</td>\n",
              "      <td>0.003935</td>\n",
              "      <td>0.015596</td>\n",
              "      <td>0.008142</td>\n",
              "      <td>-0.002592</td>\n",
              "      <td>-0.031988</td>\n",
              "      <td>-0.046641</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>\n",
              "    <div class=\"colab-df-buttons\">\n",
              "\n",
              "  <div class=\"colab-df-container\">\n",
              "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-53aa6628-5b9f-4fce-b9e1-bd41f6c6a9a8')\"\n",
              "            title=\"Convert this dataframe to an interactive table.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
              "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "\n",
              "  <style>\n",
              "    .colab-df-container {\n",
              "      display:flex;\n",
              "      gap: 12px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert {\n",
              "      background-color: #E8F0FE;\n",
              "      border: none;\n",
              "      border-radius: 50%;\n",
              "      cursor: pointer;\n",
              "      display: none;\n",
              "      fill: #1967D2;\n",
              "      height: 32px;\n",
              "      padding: 0 0 0 0;\n",
              "      width: 32px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert:hover {\n",
              "      background-color: #E2EBFA;\n",
              "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "      fill: #174EA6;\n",
              "    }\n",
              "\n",
              "    .colab-df-buttons div {\n",
              "      margin-bottom: 4px;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert {\n",
              "      background-color: #3B4455;\n",
              "      fill: #D2E3FC;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert:hover {\n",
              "      background-color: #434B5C;\n",
              "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "      fill: #FFFFFF;\n",
              "    }\n",
              "  </style>\n",
              "\n",
              "    <script>\n",
              "      const buttonEl =\n",
              "        document.querySelector('#df-53aa6628-5b9f-4fce-b9e1-bd41f6c6a9a8 button.colab-df-convert');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      async function convertToInteractive(key) {\n",
              "        const element = document.querySelector('#df-53aa6628-5b9f-4fce-b9e1-bd41f6c6a9a8');\n",
              "        const dataTable =\n",
              "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
              "                                                    [key], {});\n",
              "        if (!dataTable) return;\n",
              "\n",
              "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
              "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
              "          + ' to learn more about interactive tables.';\n",
              "        element.innerHTML = '';\n",
              "        dataTable['output_type'] = 'display_data';\n",
              "        await google.colab.output.renderOutput(dataTable, element);\n",
              "        const docLink = document.createElement('div');\n",
              "        docLink.innerHTML = docLinkHtml;\n",
              "        element.appendChild(docLink);\n",
              "      }\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "\n",
              "    </div>\n",
              "  </div>\n"
            ],
            "text/plain": [
              "        age       sex       bmi        bp        s1        s2        s3  \\\n",
              "0  0.038076  0.050680  0.061696  0.021872 -0.044223 -0.034821 -0.043401   \n",
              "1 -0.001882 -0.044642 -0.051474 -0.026328 -0.008449 -0.019163  0.074412   \n",
              "2  0.085299  0.050680  0.044451 -0.005670 -0.045599 -0.034194 -0.032356   \n",
              "3 -0.089063 -0.044642 -0.011595 -0.036656  0.012191  0.024991 -0.036038   \n",
              "4  0.005383 -0.044642 -0.036385  0.021872  0.003935  0.015596  0.008142   \n",
              "\n",
              "         s4        s5        s6  \n",
              "0 -0.002592  0.019907 -0.017646  \n",
              "1 -0.039493 -0.068332 -0.092204  \n",
              "2 -0.002592  0.002861 -0.025930  \n",
              "3  0.034309  0.022688 -0.009362  \n",
              "4 -0.002592 -0.031988 -0.046641  "
            ]
          },
          "execution_count": 8,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from sklearn.datasets import load_diabetes\n",
        "\n",
        "# Cargar los datos\n",
        "diabetes = load_diabetes()\n",
        "df = pd.DataFrame(diabetes.data, columns=diabetes.feature_names)\n",
        "\n",
        "# Ver las primeras 5 filas de los datos\n",
        "df.head()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 491
        },
        "id": "x4kqRlbnrBuK",
        "outputId": "b9664dd1-1817-417a-915c-7a267b3e54c2"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Exactitud del Modelo: 80.45%\n"
          ]
        },
        {
          "data": {
            "image/png": "[encoded data, 31536 characters]\n",
            "text/plain": [
              "<Figure size 640x480 with 2 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "from sklearn.linear_model import LogisticRegression\n",
        "from sklearn.model_selection import train_test_split\n",
        "from sklearn.metrics import accuracy_score, confusion_matrix, ConfusionMatrixDisplay\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "# Cargar los datos\n",
        "diabetes = load_diabetes()\n",
        "df = pd.DataFrame(diabetes.data, columns=diabetes.feature_names)\n",
        "df['OUTCOME'] = diabetes.target\n",
        "\n",
        "# Transformar la variable target en binaria (clasificación)\n",
        "df['OUTCOME'] = (df['OUTCOME'] > df['OUTCOME'].median()).astype(int) # 1 cuando es superior a la mediana, y 0 cuando es inferior\n",
        "\n",
        "# Dividir los datos en datos de entrenamiento y datos de prueba\n",
        "X = df.drop('OUTCOME', axis=1)\n",
        "y = df['OUTCOME']\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
        "\n",
        "# Entrenar el modelo\n",
        "model = LogisticRegression(max_iter=1000) # Aumentando las iteraciones para evitar warnings\n",
        "model.fit(X_train, y_train)\n",
        "\n",
        "# Realizar la Previsión\n",
        "y_pred = model.predict(X_test)\n",
        "\n",
        "# Evaluar el modelo\n",
        "accuracy = accuracy_score(y_test, y_pred)\n",
        "print(f'Exactitud del Modelo: {accuracy * 100:.2f}%')\n",
        "\n",
        "# Matriz de Confusión\n",
        "cm = confusion_matrix(y_test, y_pred)\n",
        "disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=['No Diabético', 'Diabético'])\n",
        "disp.plot(cmap=plt.cm.Blues)\n",
        "plt.title(\"Matriz de Confusión - Diagnóstico de Diabetes\")\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "w4rB2bbpxN7C",
        "outputId": "79d78f6b-891e-4c40-a926-fffbcc804f95"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Mejores parámetros: {'max_depth': 10, 'min_samples_leaf': 4, 'min_samples_split': 10}\n"
          ]
        }
      ],
      "source": [
        "from sklearn.datasets import fetch_california_housing\n",
        "from sklearn.model_selection import train_test_split, GridSearchCV\n",
        "from sklearn.tree import DecisionTreeRegressor\n",
        "\n",
        "# Cargar dataset\n",
        "X, y = fetch_california_housing(return_X_y=True)\n",
        "\n",
        "# Dividir en datos de entrenamiento y datos de prueba\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
        "\n",
        "# Definir los hiperparámetros para optimizarlos\n",
        "param_grid = {\n",
        "    'max_depth': [3, 5, 7, 10],\n",
        "    'min_samples_split': [2, 5, 10],\n",
        "    'min_samples_leaf': [1, 2, 4]\n",
        "}\n",
        "\n",
        "# Aplicar GridSearchCV para encontrar los mejores hiperparámetros\n",
        "grid_search = GridSearchCV(DecisionTreeRegressor(), param_grid, cv=5, scoring='neg_mean_squared_error')\n",
        "grid_search.fit(X_train, y_train)\n",
        "\n",
        "# GridSearchCV -> Realiza la búsqueda de los mejores hiperparámetros combinando todos los valores de hiperparámetros\n",
        "# Métrica de evaluación -> Error Cuadrático Medio Negativo\n",
        "print(f'Mejores parámetros: {grid_search.best_params_}')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 487
        },
        "id": "sEAcrFpL2f_a",
        "outputId": "6fd9b305-67fd-4990-98f8-b72877c2fc07"
      },
      "outputs": [
        {
          "data": {
            "image/png": "[encoded data, 25432 characters]\n",
            "text/plain": [
              "<Figure size 1000x600 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "# Importar bibliotecas\n",
        "import pandas as pd\n",
        "from sklearn.datasets import load_diabetes\n",
        "from sklearn.model_selection import train_test_split\n",
        "from sklearn.ensemble import RandomForestRegressor\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "# Cargar el dataset Diabetes\n",
        "diabetes = load_diabetes()\n",
        "X = diabetes.data # Variables independientes\n",
        "y = diabetes.target # Variable dependiente\n",
        "\n",
        "# Dividir los datos para entrenamiento y para prueba (70% treino, 30% teste)\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
        "\n",
        "# Crear y entrenar el modelo RandomForestRegressor\n",
        "model = RandomForestRegressor()\n",
        "model.fit(X_train, y_train)\n",
        "\n",
        "# Obtener la importancia de los atributos\n",
        "importances = model.feature_importances_\n",
        "feature_names = diabetes.feature_names\n",
        "\n",
        "# Crear un gráfico de barras para visualizar la importancia de los atributos\n",
        "plt.figure(figsize=(10, 6))\n",
        "plt.barh(feature_names, importances)\n",
        "plt.title(\"Importancia de los Atributos\")\n",
        "plt.xlabel(\"Importancia\")\n",
        "plt.ylabel(\"Atributo\")\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "background_save": true
        },
        "id": "149LHIAXS0r9",
        "outputId": "ebefd6fc-07d6-46ed-99a0-6ce6c3a08f7a"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Random Forest - MSE: 0.29, R²: 0.78\n",
            "Gradient Boosting - MSE: 0.24, R²: 0.82\n"
          ]
        },
        {
          "data": {
            "image/png": "[encoded data, 373800 characters]\n",
            "text/plain": [
              "<Figure size 1200x500 with 2 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "import numpy as np\n",
        "import pandas as pd\n",
        "import matplotlib.pyplot as plt\n",
        "import seaborn as sns\n",
        "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n",
        "from sklearn.model_selection import train_test_split\n",
        "from sklearn.metrics import mean_squared_error, r2_score\n",
        "from sklearn.datasets import fetch_california_housing\n",
        "\n",
        "# Cargar el conjunto de datos\n",
        "california = fetch_california_housing()\n",
        "df = pd.DataFrame(california.data, columns=california.feature_names)\n",
        "df['PRICE'] = california.target\n",
        "\n",
        "# Dividir los datos en entrenamiento y prueba\n",
        "X = df.drop('PRICE', axis=1)\n",
        "y = df['PRICE']\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
        "\n",
        "# Crear y entrenar los modelos ensemble (Ensamblados)\n",
        "rf_model = RandomForestRegressor(n_estimators=200, max_depth=10, random_state=42)\n",
        "gb_model = GradientBoostingRegressor(n_estimators=200, learning_rate=0.05, max_depth=5, random_state=42)\n",
        "rf_model.fit(X_train, y_train)\n",
        "gb_model.fit(X_train, y_train)\n",
        "\n",
        "# Realizar previsiones\n",
        "y_pred_rf = rf_model.predict(X_test)\n",
        "y_pred_gb = gb_model.predict(X_test)\n",
        "\n",
        "# Evaluar los modelos\n",
        "mse_rf = mean_squared_error(y_test, y_pred_rf)\n",
        "r2_rf = r2_score(y_test, y_pred_rf)\n",
        "mse_gb = mean_squared_error(y_test, y_pred_gb)\n",
        "r2_gb = r2_score(y_test, y_pred_gb)\n",
        "\n",
        "# Exhibir métricas\n",
        "print(f\"Random Forest - MSE: {mse_rf:.2f}, R²: {r2_rf:.2f}\")\n",
        "print(f\"Gradient Boosting - MSE: {mse_gb:.2f}, R²: {r2_gb:.2f}\")\n",
        "\n",
        "# Visualizar los resultados\n",
        "plt.figure(figsize=(12, 5))\n",
        "plt.subplot(1, 2, 1)\n",
        "sns.scatterplot(x=y_test, y=y_pred_rf, alpha=0.6)\n",
        "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], '--r', linewidth=2)\n",
        "plt.xlabel(\"Valores Reales\")\n",
        "plt.ylabel(\"Valores Previstos\")\n",
        "plt.title(\"Random Forest\")\n",
        "\n",
        "plt.subplot(1, 2, 2)\n",
        "sns.scatterplot(x=y_test, y=y_pred_gb, alpha=0.6, color='green')\n",
        "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], '--r', linewidth=2)\n",
        "plt.xlabel(\"Valores Reales\")\n",
        "plt.ylabel(\"Valores Previstos\")\n",
        "plt.title(\"Gradient Boosting\")\n",
        "\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# **Clase 3**\n",
        "## Aprendizaje No Supervisado - Clustering"
      ],
      "metadata": {
        "id": "-l7fn1ZChaHb"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn.datasets import load_iris\n",
        "import pandas as pd\n",
        "from sklearn.cluster import KMeans\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "# Cargar Dataset\n",
        "iris = load_iris()\n",
        "X = iris.data\n",
        "\n",
        "# Aplicar K-Means\n",
        "kmeans = KMeans(n_clusters=3, random_state=42)\n",
        "clusters = kmeans.fit_predict(X)\n",
        "\n",
        "# Visualizar los clusters\n",
        "plt.scatter(X[:, 0], X[:, 1], c=clusters, cmap='viridis')\n",
        "plt.title(\"Agrupando con K-Means\")\n",
        "plt.xlabel(\"Caracteristica 1\")\n",
        "plt.ylabel(\"Caracteristica 2\")\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 472
        },
        "id": "IZ-lniPxhZcf",
        "outputId": "be06ba67-a1ca-420f-85c5-8b67852d02e7"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 640x480 with 1 Axes>"
            ],
            "image/png": "[encoded data, 50388 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn.datasets import load_iris\n",
        "import scipy.cluster.hierarchy as sch\n",
        "import matplotlib.pyplot as plt\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "\n",
        "# Cargar el dataset Iris\n",
        "iris = load_iris()\n",
        "X = iris.data\n",
        "\n",
        "# Normalizar los datos para mejorar el desempeño del clustering\n",
        "scaler = StandardScaler()\n",
        "X_scaled = scaler.fit_transform(X)\n",
        "\n",
        "# Crear el dendrograma\n",
        "plt.figure(figsize=(10, 5))\n",
        "sch.dendrogram(sch.linkage(X_scaled, method='ward'))\n",
        "plt.title(\"Dendrograma del Agrupamiento Jerárquico\")\n",
        "plt.xlabel(\"Muestras\")\n",
        "plt.ylabel(\"Distancia Eucliadiana\")\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 425
        },
        "id": "mHXkc4rXsVZS",
        "outputId": "7dd7f28a-3c78-4b20-bbc9-c353e1b4ebe5"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x500 with 1 Axes>"
            ],
            "image/png": "[encoded data, 40028 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn.cluster import AgglomerativeClustering\n",
        "\n",
        "# Aplicar Hierarchical Clustering definiendo 3 grupos\n",
        "hc = AgglomerativeClustering(n_clusters=3, metric='euclidean', linkage='ward')\n",
        "clusters = hc.fit_predict(X_scaled)\n",
        "\n",
        "# Visualizar los clusters\n",
        "plt.scatter(X[:, 0], X[:, 1], c=clusters, cmap='viridis')\n",
        "plt.title(\"Agrupando con Hierarchical Clustering\")\n",
        "plt.xlabel(\"Caracteristica 1\")\n",
        "plt.ylabel(\"Caracteristica 2\")\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 472
        },
        "id": "zc2n_rRpss05",
        "outputId": "877091c0-8aa3-4b34-bc6c-28343a21ca35"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 640x480 with 1 Axes>"
            ],
            "image/png": "[encoded data, 52352 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Aprendizaje No Supervisado - PCA"
      ],
      "metadata": {
        "id": "8cyJGHKJykxo"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn.decomposition import PCA\n",
        "from sklearn.datasets import load_iris\n",
        "import matplotlib.pyplot as plt\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "\n",
        "# Cargar el dataset Iris\n",
        "iris = load_iris()\n",
        "X = iris.data\n",
        "y = iris.target # Etiquetas de las especies de flores\n",
        "\n",
        "# Normalizar los datos para mejorar el desempeño\n",
        "scaler = StandardScaler()\n",
        "X_scaled = scaler.fit_transform(X)\n",
        "\n",
        "# Aplicar PCA para reducir de 4 a dos dimensiones\n",
        "pca = PCA(n_components=2)\n",
        "X_pca = pca.fit_transform(X_scaled)\n",
        "\n",
        "# Visualizar los datos reducidos\n",
        "plt.figure(figsize=(8, 6))\n",
        "plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis', alpha=0.7)\n",
        "plt.xlabel(\"Componente Principal 1\")\n",
        "plt.ylabel(\"Componente Principal 2\")\n",
        "plt.title(\"Reducción de la Dimensionalidad con PCA\")\n",
        "plt.colorbar(label=\"Especies de Flores\")\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 564
        },
        "id": "aiOR1kTIyoRN",
        "outputId": "413f06d3-c776-4a54-bc6a-d778f7793022"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 800x600 with 2 Axes>"
            ],
            "image/png": "[encoded data, 89040 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(pca.explained_variance_ratio_)\n",
        "print(f\"Varianza acumulada: {sum(pca.explained_variance_ratio_):.2f}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "e4USH46X0mQM",
        "outputId": "9ad4268d-bf30-45d4-84bc-3d1b8b431517"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[0.72962445 0.22850762]\n",
            "Varianza acumulada: 0.96\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# **Clase 4**\n",
        "## Procesamiento de imágenes"
      ],
      "metadata": {
        "id": "DZSZUimH5gu2"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import cv2\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "from google.colab import files\n",
        "\n",
        "# Realizar upload de la Imagen\n",
        "uploaded = files.upload()\n",
        "image_path = list(uploaded.keys())[0]\n",
        "\n",
        "# Cargar la imagen en escala de grises\n",
        "imagen = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n",
        "\n",
        "# Mostrar la imagen original y la matriz correspondiente\n",
        "plt.figure(figsize=(15,8))\n",
        "\n",
        "plt.subplot(1, 2, 1)\n",
        "plt.imshow(imagen, cmap=\"gray\")\n",
        "plt.title(\"Imagen en tonos de gris\")\n",
        "plt.axis(\"off\")\n",
        "\n",
        "plt.subplot(1, 2, 2)\n",
        "plt.imshow(imagen, cmap=\"gray\")\n",
        "plt.title(\"Matriz de Pixeles\")\n",
        "for i in range(0, imagen.shape[0], 30):\n",
        "    for j in range(0, imagen.shape[1], 30):\n",
        "        plt.text(j, i, str(imagen[i, j]), color=\"red\", fontsize=6, ha='center', va='center')\n",
        "\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 531
        },
        "id": "dHyh8vyA5ch1",
        "outputId": "786efd11-bcc6-4c77-bd30-9cfb84f24b7f"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ],
            "text/html": [
              "\n",
              "     <input type=\"file\" id=\"files-1a66b318-c464-4ccb-a608-f61c11e19953\" name=\"files[]\" multiple disabled\n",
              "        style=\"border:none\" />\n",
              "     <output id=\"result-1a66b318-c464-4ccb-a608-f61c11e19953\">\n",
              "      Upload widget is only available when the cell has been executed in the\n",
              "      current browser session. Please rerun this cell to enable.\n",
              "      </output>\n",
              "      <script>// Copyright 2017 Google LLC\n",
              "//\n",
              "// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
              "// you may not use this file except in compliance with the License.\n",
              "// You may obtain a copy of the License at\n",
              "//\n",
              "//      http://www.apache.org/licenses/LICENSE-2.0\n",
              "//\n",
              "// Unless required by applicable law or agreed to in writing, software\n",
              "// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
              "// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
              "// See the License for the specific language governing permissions and\n",
              "// limitations under the License.\n",
              "\n",
              "/**\n",
              " * @fileoverview Helpers for google.colab Python module.\n",
              " */\n",
              "(function(scope) {\n",
              "function span(text, styleAttributes = {}) {\n",
              "  const element = document.createElement('span');\n",
              "  element.textContent = text;\n",
              "  for (const key of Object.keys(styleAttributes)) {\n",
              "    element.style[key] = styleAttributes[key];\n",
              "  }\n",
              "  return element;\n",
              "}\n",
              "\n",
              "// Max number of bytes which will be uploaded at a time.\n",
              "const MAX_PAYLOAD_SIZE = 100 * 1024;\n",
              "\n",
              "function _uploadFiles(inputId, outputId) {\n",
              "  const steps = uploadFilesStep(inputId, outputId);\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  // Cache steps on the outputElement to make it available for the next call\n",
              "  // to uploadFilesContinue from Python.\n",
              "  outputElement.steps = steps;\n",
              "\n",
              "  return _uploadFilesContinue(outputId);\n",
              "}\n",
              "\n",
              "// This is roughly an async generator (not supported in the browser yet),\n",
              "// where there are multiple asynchronous steps and the Python side is going\n",
              "// to poll for completion of each step.\n",
              "// This uses a Promise to block the python side on completion of each step,\n",
              "// then passes the result of the previous step as the input to the next step.\n",
              "function _uploadFilesContinue(outputId) {\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  const steps = outputElement.steps;\n",
              "\n",
              "  const next = steps.next(outputElement.lastPromiseValue);\n",
              "  return Promise.resolve(next.value.promise).then((value) => {\n",
              "    // Cache the last promise value to make it available to the next\n",
              "    // step of the generator.\n",
              "    outputElement.lastPromiseValue = value;\n",
              "    return next.value.response;\n",
              "  });\n",
              "}\n",
              "\n",
              "/**\n",
              " * Generator function which is called between each async step of the upload\n",
              " * process.\n",
              " * @param {string} inputId Element ID of the input file picker element.\n",
              " * @param {string} outputId Element ID of the output display.\n",
              " * @return {!Iterable<!Object>} Iterable of next steps.\n",
              " */\n",
              "function* uploadFilesStep(inputId, outputId) {\n",
              "  const inputElement = document.getElementById(inputId);\n",
              "  inputElement.disabled = false;\n",
              "\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  outputElement.innerHTML = '';\n",
              "\n",
              "  const pickedPromise = new Promise((resolve) => {\n",
              "    inputElement.addEventListener('change', (e) => {\n",
              "      resolve(e.target.files);\n",
              "    });\n",
              "  });\n",
              "\n",
              "  const cancel = document.createElement('button');\n",
              "  inputElement.parentElement.appendChild(cancel);\n",
              "  cancel.textContent = 'Cancel upload';\n",
              "  const cancelPromise = new Promise((resolve) => {\n",
              "    cancel.onclick = () => {\n",
              "      resolve(null);\n",
              "    };\n",
              "  });\n",
              "\n",
              "  // Wait for the user to pick the files.\n",
              "  const files = yield {\n",
              "    promise: Promise.race([pickedPromise, cancelPromise]),\n",
              "    response: {\n",
              "      action: 'starting',\n",
              "    }\n",
              "  };\n",
              "\n",
              "  cancel.remove();\n",
              "\n",
              "  // Disable the input element since further picks are not allowed.\n",
              "  inputElement.disabled = true;\n",
              "\n",
              "  if (!files) {\n",
              "    return {\n",
              "      response: {\n",
              "        action: 'complete',\n",
              "      }\n",
              "    };\n",
              "  }\n",
              "\n",
              "  for (const file of files) {\n",
              "    const li = document.createElement('li');\n",
              "    li.append(span(file.name, {fontWeight: 'bold'}));\n",
              "    li.append(span(\n",
              "        `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n",
              "        `last modified: ${\n",
              "            file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n",
              "                                    'n/a'} - `));\n",
              "    const percent = span('0% done');\n",
              "    li.appendChild(percent);\n",
              "\n",
              "    outputElement.appendChild(li);\n",
              "\n",
              "    const fileDataPromise = new Promise((resolve) => {\n",
              "      const reader = new FileReader();\n",
              "      reader.onload = (e) => {\n",
              "        resolve(e.target.result);\n",
              "      };\n",
              "      reader.readAsArrayBuffer(file);\n",
              "    });\n",
              "    // Wait for the data to be ready.\n",
              "    let fileData = yield {\n",
              "      promise: fileDataPromise,\n",
              "      response: {\n",
              "        action: 'continue',\n",
              "      }\n",
              "    };\n",
              "\n",
              "    // Use a chunked sending to avoid message size limits. See b/62115660.\n",
              "    let position = 0;\n",
              "    do {\n",
              "      const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n",
              "      const chunk = new Uint8Array(fileData, position, length);\n",
              "      position += length;\n",
              "\n",
              "      const base64 = btoa(String.fromCharCode.apply(null, chunk));\n",
              "      yield {\n",
              "        response: {\n",
              "          action: 'append',\n",
              "          file: file.name,\n",
              "          data: base64,\n",
              "        },\n",
              "      };\n",
              "\n",
              "      let percentDone = fileData.byteLength === 0 ?\n",
              "          100 :\n",
              "          Math.round((position / fileData.byteLength) * 100);\n",
              "      percent.textContent = `${percentDone}% done`;\n",
              "\n",
              "    } while (position < fileData.byteLength);\n",
              "  }\n",
              "\n",
              "  // All done.\n",
              "  yield {\n",
              "    response: {\n",
              "      action: 'complete',\n",
              "    }\n",
              "  };\n",
              "}\n",
              "\n",
              "scope.google = scope.google || {};\n",
              "scope.google.colab = scope.google.colab || {};\n",
              "scope.google.colab._files = {\n",
              "  _uploadFiles,\n",
              "  _uploadFilesContinue,\n",
              "};\n",
              "})(self);\n",
              "</script> "
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Saving Re_Zero_Volume_42_Inside_Cover.webp to Re_Zero_Volume_42_Inside_Cover.webp\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1500x800 with 2 Axes>"
            ],
            "image/png": "[encoded data, 986732 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from tensorflow.keras.models import Sequential\n",
        "from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\n",
        "\n",
        "# Crear un modelo CNN simple\n",
        "modelo = Sequential([\n",
        "    Conv2D(32, (3,3), activation='relu', input_shape=(64, 64, 3)), # Capa convolucional\n",
        "    MaxPooling2D(pool_size=(2,2)), # Capa de pooling\n",
        "    Flatten(), # Aplanando para la capa densa\n",
        "    Dense(128, activation='relu'), # Capa totalmente conectada\n",
        "    Dense(3, activation='softmax') # Salida para 3 clases\n",
        "])\n",
        "\n",
        "modelo.summary() # Exhibe la arquitectura de la red"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 347
        },
        "id": "h1x0gW-E-7FF",
        "outputId": "bb077d4f-a187-42c7-b7ac-41116beb9054"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.12/dist-packages/keras/src/layers/convolutional/base_conv.py:113: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead.\n",
            "  super().__init__(activity_regularizer=activity_regularizer, **kwargs)\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "\u001b[1mModel: \"sequential\"\u001b[0m\n"
            ],
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">Model: \"sequential\"</span>\n",
              "</pre>\n"
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓\n",
              "┃\u001b[1m \u001b[0m\u001b[1mLayer (type)                   \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mOutput Shape          \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1m      Param #\u001b[0m\u001b[1m \u001b[0m┃\n",
              "┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩\n",
              "│ conv2d (\u001b[38;5;33mConv2D\u001b[0m)                 │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m62\u001b[0m, \u001b[38;5;34m62\u001b[0m, \u001b[38;5;34m32\u001b[0m)     │           \u001b[38;5;34m896\u001b[0m │\n",
              "├─────────────────────────────────┼────────────────────────┼───────────────┤\n",
              "│ max_pooling2d (\u001b[38;5;33mMaxPooling2D\u001b[0m)    │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m31\u001b[0m, \u001b[38;5;34m31\u001b[0m, \u001b[38;5;34m32\u001b[0m)     │             \u001b[38;5;34m0\u001b[0m │\n",
              "├─────────────────────────────────┼────────────────────────┼───────────────┤\n",
              "│ flatten (\u001b[38;5;33mFlatten\u001b[0m)               │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m30752\u001b[0m)          │             \u001b[38;5;34m0\u001b[0m │\n",
              "├─────────────────────────────────┼────────────────────────┼───────────────┤\n",
              "│ dense (\u001b[38;5;33mDense\u001b[0m)                   │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m128\u001b[0m)            │     \u001b[38;5;34m3,936,384\u001b[0m │\n",
              "├─────────────────────────────────┼────────────────────────┼───────────────┤\n",
              "│ dense_1 (\u001b[38;5;33mDense\u001b[0m)                 │ (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m3\u001b[0m)              │           \u001b[38;5;34m387\u001b[0m │\n",
              "└─────────────────────────────────┴────────────────────────┴───────────────┘\n"
            ],
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓\n",
              "┃<span style=\"font-weight: bold\"> Layer (type)                    </span>┃<span style=\"font-weight: bold\"> Output Shape           </span>┃<span style=\"font-weight: bold\">       Param # </span>┃\n",
              "┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩\n",
              "│ conv2d (<span style=\"color: #0087ff; text-decoration-color: #0087ff\">Conv2D</span>)                 │ (<span style=\"color: #00d7ff; text-decoration-color: #00d7ff\">None</span>, <span style=\"color: #00af00; text-decoration-color: #00af00\">62</span>, <span style=\"color: #00af00; text-decoration-color: #00af00\">62</span>, <span style=\"color: #00af00; text-decoration-color: #00af00\">32</span>)     │           <span style=\"color: #00af00; text-decoration-color: #00af00\">896</span> │\n",
              "├─────────────────────────────────┼────────────────────────┼───────────────┤\n",
              "│ max_pooling2d (<span style=\"color: #0087ff; text-decoration-color: #0087ff\">MaxPooling2D</span>)    │ (<span style=\"color: #00d7ff; text-decoration-color: #00d7ff\">None</span>, <span style=\"color: #00af00; text-decoration-color: #00af00\">31</span>, <span style=\"color: #00af00; text-decoration-color: #00af00\">31</span>, <span style=\"color: #00af00; text-decoration-color: #00af00\">32</span>)     │             <span style=\"color: #00af00; text-decoration-color: #00af00\">0</span> │\n",
              "├─────────────────────────────────┼────────────────────────┼───────────────┤\n",
              "│ flatten (<span style=\"color: #0087ff; text-decoration-color: #0087ff\">Flatten</span>)               │ (<span style=\"color: #00d7ff; text-decoration-color: #00d7ff\">None</span>, <span style=\"color: #00af00; text-decoration-color: #00af00\">30752</span>)          │             <span style=\"color: #00af00; text-decoration-color: #00af00\">0</span> │\n",
              "├─────────────────────────────────┼────────────────────────┼───────────────┤\n",
              "│ dense (<span style=\"color: #0087ff; text-decoration-color: #0087ff\">Dense</span>)                   │ (<span style=\"color: #00d7ff; text-decoration-color: #00d7ff\">None</span>, <span style=\"color: #00af00; text-decoration-color: #00af00\">128</span>)            │     <span style=\"color: #00af00; text-decoration-color: #00af00\">3,936,384</span> │\n",
              "├─────────────────────────────────┼────────────────────────┼───────────────┤\n",
              "│ dense_1 (<span style=\"color: #0087ff; text-decoration-color: #0087ff\">Dense</span>)                 │ (<span style=\"color: #00d7ff; text-decoration-color: #00d7ff\">None</span>, <span style=\"color: #00af00; text-decoration-color: #00af00\">3</span>)              │           <span style=\"color: #00af00; text-decoration-color: #00af00\">387</span> │\n",
              "└─────────────────────────────────┴────────────────────────┴───────────────┘\n",
              "</pre>\n"
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "\u001b[1m Total params: \u001b[0m\u001b[38;5;34m3,937,667\u001b[0m (15.02 MB)\n"
            ],
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\"> Total params: </span><span style=\"color: #00af00; text-decoration-color: #00af00\">3,937,667</span> (15.02 MB)\n",
              "</pre>\n"
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "\u001b[1m Trainable params: \u001b[0m\u001b[38;5;34m3,937,667\u001b[0m (15.02 MB)\n"
            ],
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\"> Trainable params: </span><span style=\"color: #00af00; text-decoration-color: #00af00\">3,937,667</span> (15.02 MB)\n",
              "</pre>\n"
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "\u001b[1m Non-trainable params: \u001b[0m\u001b[38;5;34m0\u001b[0m (0.00 B)\n"
            ],
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\"> Non-trainable params: </span><span style=\"color: #00af00; text-decoration-color: #00af00\">0</span> (0.00 B)\n",
              "</pre>\n"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from tensorflow.keras.applications import MobileNetV2\n",
        "from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions\n",
        "import numpy as np\n",
        "import cv2\n",
        "from google.colab import files\n",
        "from PIL import Image\n",
        "\n",
        "# Fazer upload de imagen\n",
        "uploaded = files.upload()\n",
        "imagen_path = list(uploaded.keys())[0] # Toma el nombre del archivo enviado\n",
        "\n",
        "# Cargar la imagen usando OpenCV\n",
        "imagen = cv2.imread(imagen_path)\n",
        "imagen_rgb = cv2.cvtColor(imagen, cv2.COLOR_BGR2RGB)\n",
        "\n",
        "# Cargar el modelo MobileNetV2 pre-entrenado\n",
        "modelo = MobileNetV2(weights=\"imagenet\")\n",
        "\n",
        "# Pre-procesar la imagen para el formato esperado por el modelo\n",
        "imagen_redimensionada = cv2.resize(imagen_rgb, (224, 224))\n",
        "imagen_array = np.expand_dims(imagen_redimensionada, axis=0)\n",
        "imagen_array = preprocess_input(imagen_array)\n",
        "\n",
        "# Fazer a previsão\n",
        "previsiones = modelo.predict(imagen_array)\n",
        "label = decode_predictions(previsiones)\n",
        "print(\"Objeto identificado:\", label[0][0][1]) # Exhibe la clase identificada"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 226
        },
        "id": "t2-jTo-eD2CI",
        "outputId": "0b8ea5ce-f40e-491a-fc85-fd2538e67788"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ],
            "text/html": [
              "\n",
              "     <input type=\"file\" id=\"files-664fa369-3125-4ed8-bbcc-a1d3d82a3e85\" name=\"files[]\" multiple disabled\n",
              "        style=\"border:none\" />\n",
              "     <output id=\"result-664fa369-3125-4ed8-bbcc-a1d3d82a3e85\">\n",
              "      Upload widget is only available when the cell has been executed in the\n",
              "      current browser session. Please rerun this cell to enable.\n",
              "      </output>\n",
              "      <script>// Copyright 2017 Google LLC\n",
              "//\n",
              "// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
              "// you may not use this file except in compliance with the License.\n",
              "// You may obtain a copy of the License at\n",
              "//\n",
              "//      http://www.apache.org/licenses/LICENSE-2.0\n",
              "//\n",
              "// Unless required by applicable law or agreed to in writing, software\n",
              "// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
              "// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
              "// See the License for the specific language governing permissions and\n",
              "// limitations under the License.\n",
              "\n",
              "/**\n",
              " * @fileoverview Helpers for google.colab Python module.\n",
              " */\n",
              "(function(scope) {\n",
              "function span(text, styleAttributes = {}) {\n",
              "  const element = document.createElement('span');\n",
              "  element.textContent = text;\n",
              "  for (const key of Object.keys(styleAttributes)) {\n",
              "    element.style[key] = styleAttributes[key];\n",
              "  }\n",
              "  return element;\n",
              "}\n",
              "\n",
              "// Max number of bytes which will be uploaded at a time.\n",
              "const MAX_PAYLOAD_SIZE = 100 * 1024;\n",
              "\n",
              "function _uploadFiles(inputId, outputId) {\n",
              "  const steps = uploadFilesStep(inputId, outputId);\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  // Cache steps on the outputElement to make it available for the next call\n",
              "  // to uploadFilesContinue from Python.\n",
              "  outputElement.steps = steps;\n",
              "\n",
              "  return _uploadFilesContinue(outputId);\n",
              "}\n",
              "\n",
              "// This is roughly an async generator (not supported in the browser yet),\n",
              "// where there are multiple asynchronous steps and the Python side is going\n",
              "// to poll for completion of each step.\n",
              "// This uses a Promise to block the python side on completion of each step,\n",
              "// then passes the result of the previous step as the input to the next step.\n",
              "function _uploadFilesContinue(outputId) {\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  const steps = outputElement.steps;\n",
              "\n",
              "  const next = steps.next(outputElement.lastPromiseValue);\n",
              "  return Promise.resolve(next.value.promise).then((value) => {\n",
              "    // Cache the last promise value to make it available to the next\n",
              "    // step of the generator.\n",
              "    outputElement.lastPromiseValue = value;\n",
              "    return next.value.response;\n",
              "  });\n",
              "}\n",
              "\n",
              "/**\n",
              " * Generator function which is called between each async step of the upload\n",
              " * process.\n",
              " * @param {string} inputId Element ID of the input file picker element.\n",
              " * @param {string} outputId Element ID of the output display.\n",
              " * @return {!Iterable<!Object>} Iterable of next steps.\n",
              " */\n",
              "function* uploadFilesStep(inputId, outputId) {\n",
              "  const inputElement = document.getElementById(inputId);\n",
              "  inputElement.disabled = false;\n",
              "\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  outputElement.innerHTML = '';\n",
              "\n",
              "  const pickedPromise = new Promise((resolve) => {\n",
              "    inputElement.addEventListener('change', (e) => {\n",
              "      resolve(e.target.files);\n",
              "    });\n",
              "  });\n",
              "\n",
              "  const cancel = document.createElement('button');\n",
              "  inputElement.parentElement.appendChild(cancel);\n",
              "  cancel.textContent = 'Cancel upload';\n",
              "  const cancelPromise = new Promise((resolve) => {\n",
              "    cancel.onclick = () => {\n",
              "      resolve(null);\n",
              "    };\n",
              "  });\n",
              "\n",
              "  // Wait for the user to pick the files.\n",
              "  const files = yield {\n",
              "    promise: Promise.race([pickedPromise, cancelPromise]),\n",
              "    response: {\n",
              "      action: 'starting',\n",
              "    }\n",
              "  };\n",
              "\n",
              "  cancel.remove();\n",
              "\n",
              "  // Disable the input element since further picks are not allowed.\n",
              "  inputElement.disabled = true;\n",
              "\n",
              "  if (!files) {\n",
              "    return {\n",
              "      response: {\n",
              "        action: 'complete',\n",
              "      }\n",
              "    };\n",
              "  }\n",
              "\n",
              "  for (const file of files) {\n",
              "    const li = document.createElement('li');\n",
              "    li.append(span(file.name, {fontWeight: 'bold'}));\n",
              "    li.append(span(\n",
              "        `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n",
              "        `last modified: ${\n",
              "            file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n",
              "                                    'n/a'} - `));\n",
              "    const percent = span('0% done');\n",
              "    li.appendChild(percent);\n",
              "\n",
              "    outputElement.appendChild(li);\n",
              "\n",
              "    const fileDataPromise = new Promise((resolve) => {\n",
              "      const reader = new FileReader();\n",
              "      reader.onload = (e) => {\n",
              "        resolve(e.target.result);\n",
              "      };\n",
              "      reader.readAsArrayBuffer(file);\n",
              "    });\n",
              "    // Wait for the data to be ready.\n",
              "    let fileData = yield {\n",
              "      promise: fileDataPromise,\n",
              "      response: {\n",
              "        action: 'continue',\n",
              "      }\n",
              "    };\n",
              "\n",
              "    // Use a chunked sending to avoid message size limits. See b/62115660.\n",
              "    let position = 0;\n",
              "    do {\n",
              "      const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n",
              "      const chunk = new Uint8Array(fileData, position, length);\n",
              "      position += length;\n",
              "\n",
              "      const base64 = btoa(String.fromCharCode.apply(null, chunk));\n",
              "      yield {\n",
              "        response: {\n",
              "          action: 'append',\n",
              "          file: file.name,\n",
              "          data: base64,\n",
              "        },\n",
              "      };\n",
              "\n",
              "      let percentDone = fileData.byteLength === 0 ?\n",
              "          100 :\n",
              "          Math.round((position / fileData.byteLength) * 100);\n",
              "      percent.textContent = `${percentDone}% done`;\n",
              "\n",
              "    } while (position < fileData.byteLength);\n",
              "  }\n",
              "\n",
              "  // All done.\n",
              "  yield {\n",
              "    response: {\n",
              "      action: 'complete',\n",
              "    }\n",
              "  };\n",
              "}\n",
              "\n",
              "scope.google = scope.google || {};\n",
              "scope.google.colab = scope.google.colab || {};\n",
              "scope.google.colab._files = {\n",
              "  _uploadFiles,\n",
              "  _uploadFilesContinue,\n",
              "};\n",
              "})(self);\n",
              "</script> "
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Saving Re_Zero_Volume_42_Inside_Cover.webp to Re_Zero_Volume_42_Inside_Cover.webp\n",
            "Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/mobilenet_v2/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_224.h5\n",
            "\u001b[1m14536120/14536120\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 0us/step\n",
            "\u001b[1m1/1\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m1s\u001b[0m 1s/step\n",
            "Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json\n",
            "\u001b[1m35363/35363\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 0us/step\n",
            "Objeto identificado: parachute\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn.feature_extraction.text import CountVectorizer\n",
        "\n",
        "# Conjunto de frases\n",
        "frases = [\"Yo amo viajar para Japón\", \"Viajar es increíble\", \"Quiero conocer Japón\"]\n",
        "\n",
        "# Creando el modelo BoW\n",
        "vectorizer = CountVectorizer()\n",
        "X = vectorizer.fit_transform(frases)\n",
        "\n",
        "# Exhibir matriz resultante\n",
        "print(vectorizer.get_feature_names_out())\n",
        "print(X.toarray())"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "LeC0BU4nJq_y",
        "outputId": "e81d645d-c571-405e-8cb9-3fbb665fb83d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "['amo' 'conocer' 'es' 'increíble' 'japón' 'para' 'quiero' 'viajar' 'yo']\n",
            "[[1 0 0 0 1 1 0 1 1]\n",
            " [0 0 1 1 0 0 0 1 0]\n",
            " [0 1 0 0 1 0 1 0 0]]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from transformers import pipeline\n",
        "\n",
        "# Cargar un modelo de generación de texto\n",
        "generador = pipeline(\"text-generation\", model=\"gpt2\")\n",
        "\n",
        "# Definir el prompt\n",
        "prompt = \"Cuál es la mejor época para visitar Japón?\"\n",
        "\n",
        "# Generar una respuesta ajustando los parámetros para evitar repeticiones\n",
        "respuesta = generador(\n",
        "    prompt,\n",
        "    max_length=50,      # Aumentar un poco la longitud\n",
        "    temperature=0.1,    # Controla la aleatoriedad\n",
        "    top_p=0.9,          # Realiza el muestreo con un núcleo (nucleus sampling)\n",
        "    top_k=10,           # Restringe la elección al top 50 de palabras con mayor probabilidad\n",
        "    repetition_penalty=1.2 # Penaliza repeticiones\n",
        ")\n",
        "\n",
        "# Exhibir la respuesta formateada\n",
        "print(respuesta[0]['generated_text'])"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 183,
          "referenced_widgets": [
            "9f0e9d13394344dab2e1c735379ae613",
            "bbc73ee4ea424bf5bae48e27957bc889",
            "40d74c4c5ae2421c843e87470247aff0",
            "8fb944276bce4bfd983dcade78fa91be",
            "ac1b4947f94f4f9ca4309fe393e45c68",
            "e63de28372374d9189db77b548ff99ad",
            "cdfbed51c19d4a43bbb08013a99931a0",
            "85f3de026c614746a4caf128a70ea6d4",
            "6b7ae5a4d3f447eea26d36741b6a0244",
            "e907a6df16004d65829c5a5b8e8a218e",
            "e4e3e43018814a6a9ee5dd19eca17248"
          ]
        },
        "id": "fuSqfSMCg0y-",
        "outputId": "e7d4dc3e-cd2a-4809-a445-1bd7335e8163"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "Loading weights:   0%|          | 0/148 [00:00<?, ?it/s]"
            ],
            "application/vnd.jupyter.widget-view+json": {
              "version_major": 2,
              "version_minor": 0,
              "model_id": "9f0e9d13394344dab2e1c735379ae613"
            }
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "[transformers] Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n",
            "[transformers] Both `max_new_tokens` (=256) and `max_length`(=50) seem to have been set. `max_new_tokens` will take precedence. Please refer to the documentation for more information. (https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Cuál es la mejor época para visitar Japón?\n",
            "The following is a list of the places where you can see and hear music in Mexico. The first two are from my personal experience, but I have also heard some other things that were not mentioned here:\n",
            "\n",
            " (1) A small town called Puebla de los Muertos (Puerto Rico). It was founded by Spanish settlers who settled there about 1550 AD when they came to establish their own country on land which had been taken over during World War II as part \"the territory\" for Spain's colonial rule.[2] They built an island with its capital at La Cienega near San Juan del Sur; it has since become one of the most important tourist destinations around the world due to this location being located just outside of Puerto Rico itself! This place contains many interesting sights such like mountainsides or beaches along riverside areas while others include large cemeteries filled entirely with people looking out into space through windows overlooking sea level below them[3]. There may be more than 100 different kinds per day depending upon what kind your area needs so please feel free if visiting these locations without any prior knowledge before coming back home again!!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import gymnasium as gym\n",
        "\n",
        "# Inicializar el entorno FrozenLake\n",
        "# El agente necesita cruzar un lago congelado sin caer en los agujeros\n",
        "env = gym.make(\"FrozenLake-v1\", is_slippery=True)\n",
        "\n",
        "# Definir los hiperparámetros del Q-Learning\n",
        "alpha = 0.8  # Tasa de aprendizaje: cuánto aprende el agente de nueva información\n",
        "gamma = 0.95  # Factor de descuento: cuán importantes son las recompensas futuras en comparación con las inmediatas\n",
        "epsilon = 1.0  # Probabilidad inicial de explorar acciones aleatorias\n",
        "epsilon_decay = 0.999  # Reduce gradualmente la exploración a medida que el agente aprende\n",
        "epsilon_min = 0.01  # Límite mínimo de exploración para garantizar que el agente aún explore un poco\n",
        "num_episodes = 20000  # Número total de intentos de aprendizaje (episodios)\n",
        "\n",
        "# Crear la tabla Q (Q-table) con ceros\n",
        "# Las filas representan los estados y las columnas representan las acciones\n",
        "q_table = np.zeros((env.observation_space.n, env.action_space.n))\n",
        "\n",
        "# Iniciar el entrenamiento del agente\n",
        "for episode in range(num_episodes):\n",
        "    # Reiniciar el entorno en cada episodio\n",
        "    state, _ = env.reset()\n",
        "    done = False\n",
        "\n",
        "    while not done:\n",
        "        # Elegir una acción usando la estrategia epsilon-greedy\n",
        "        # Con probabilidad 'epsilon', elegimos una acción aleatoria (exploración)\n",
        "        # De lo contrario, elegimos la mejor acción conocida hasta el momento (explotación)\n",
        "        if np.random.rand() < epsilon:\n",
        "            action = env.action_space.sample()  # Explorar una acción aleatoria\n",
        "        else:\n",
        "            action = np.argmax(q_table[state])  # Explorar la acción con mayor valor en la Q-table\n",
        "\n",
        "        # Ejecutar la acción elegida en el entorno\n",
        "        next_state, reward, done, truncated, _ = env.step(action)\n",
        "\n",
        "        # Actualizar la Q-table con la fórmula de aprendizaje por refuerzo\n",
        "        # Q(s, a) = Q(s, a) + alpha * (recompensa + descuento * max(Q(s', a')) - Q(s, a))\n",
        "        best_next_action = np.max(q_table[next_state])  # Mejor acción en el siguiente estado\n",
        "        q_table[state, action] += alpha * (reward + gamma * best_next_action - q_table[state, action])\n",
        "\n",
        "        # Avanzar al siguiente estado\n",
        "        state = next_state\n",
        "\n",
        "    # Reducir la tasa de exploración gradualmente, sin superar el mínimo definido\n",
        "    if epsilon > epsilon_min:\n",
        "        epsilon *= epsilon_decay\n",
        "\n",
        "# Evaluar el rendimiento del agente entrenado\n",
        "# Aquí, probamos 1000 episodios para verificar cuántas veces logra cruzar el lago con éxito\n",
        "successes = 0\n",
        "for episode in range(1000):\n",
        "    state, _ = env.reset()\n",
        "    done = False\n",
        "    while not done:\n",
        "        # El agente ahora solo elige la mejor acción aprendida (sin exploración aleatoria)\n",
        "        action = np.argmax(q_table[state])\n",
        "        state, reward, done, truncated, _ = env.step(action)\n",
        "        if done and reward == 1.0:\n",
        "            successes += 1  # Contabilizar los éxitos\n",
        "\n",
        "# Mostrar el resultado final\n",
        "print(f\"El agente logró cruzar el lago con éxito en {successes} de 1000 episodios.\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "n7g_V-DL7aZ9",
        "outputId": "f05213e1-300f-4593-e37c-eeb5cfdf6bbb"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "El agente logró cruzar el lago con éxito en 836 de 1000 episodios.\n"
          ]
        }
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": [],
      "toc_visible": true,
      "authorship_tag": "ABX9TyMBnNjdIaiJPWIxJkjIJOvX",
      "include_colab_link": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    },
    "widgets": {
      "application/vnd.jupyter.widget-state+json": {
        "9f0e9d13394344dab2e1c735379ae613": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HBoxModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_bbc73ee4ea424bf5bae48e27957bc889",
              "IPY_MODEL_40d74c4c5ae2421c843e87470247aff0",
              "IPY_MODEL_8fb944276bce4bfd983dcade78fa91be"
            ],
            "layout": "IPY_MODEL_ac1b4947f94f4f9ca4309fe393e45c68"
          }
        },
        "bbc73ee4ea424bf5bae48e27957bc889": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_e63de28372374d9189db77b548ff99ad",
            "placeholder": "​",
            "style": "IPY_MODEL_cdfbed51c19d4a43bbb08013a99931a0",
            "value": "Loading weights: 100%"
          }
        },
        "40d74c4c5ae2421c843e87470247aff0": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "FloatProgressModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_85f3de026c614746a4caf128a70ea6d4",
            "max": 148,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_6b7ae5a4d3f447eea26d36741b6a0244",
            "value": 148
          }
        },
        "8fb944276bce4bfd983dcade78fa91be": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_e907a6df16004d65829c5a5b8e8a218e",
            "placeholder": "​",
            "style": "IPY_MODEL_e4e3e43018814a6a9ee5dd19eca17248",
            "value": " 148/148 [00:00&lt;00:00, 3046.72it/s]"
          }
        },
        "ac1b4947f94f4f9ca4309fe393e45c68": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "e63de28372374d9189db77b548ff99ad": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "cdfbed51c19d4a43bbb08013a99931a0": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "85f3de026c614746a4caf128a70ea6d4": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "6b7ae5a4d3f447eea26d36741b6a0244": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "ProgressStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "e907a6df16004d65829c5a5b8e8a218e": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "e4e3e43018814a6a9ee5dd19eca17248": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        }
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}