<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Robinson Miranda</title>
<link>https://robinsonmirandaco.github.io/blog.html</link>
<atom:link href="https://robinsonmirandaco.github.io/blog.xml" rel="self" type="application/rss+xml"/>
<description>Tutoriales de Machine Learning con Python, del análisis exploratorio a los modelos.</description>
<generator>quarto-1.10.18</generator>
<lastBuildDate>Thu, 08 Oct 2026 00:00:00 GMT</lastBuildDate>
<item>
  <title>Conceptos básicos de análisis de datos y Machine Learning: guía para empezar desde cero</title>
  <dc:creator>Robinson Miranda</dc:creator>
  <link>https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/</link>
  <description><![CDATA[ 






<p>Cuando empiezas en datos te encuentras con un muro de palabras: <em>feature</em>, <em>target</em>, <em>overfitting</em>, <em>train/test</em>, <em>validación cruzada</em>. Cada tutorial las usa como si ya las conocieras.</p>
<p>Este post es el que me habría gustado leer al principio (si quieres saber por qué empecé este blog, te lo cuento <a href="../bienvenida/">aquí</a>). Es un mapa de los conceptos fundamentales, explicados en lenguaje simple y en el orden en que los vas a necesitar. Puedes leerlo de corrido o usarlo como glosario y volver cuando un término te frene.</p>
<div class="callout callout-style-default callout-tip callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Tip</span>Cómo leer este post
</div>
</div>
<div class="callout-body-container callout-body">
<p>Cada concepto tiene tres partes: <strong>qué es</strong>, <strong>un ejemplo</strong> y <strong>por qué importa</strong>. Al final hay un ejemplo completo en <a href="https://www.python.org/">Python</a> que junta casi todo. Puedes ejecutarlo gratis en <a href="https://colab.research.google.com/">Google Colab</a> sin instalar nada.</p>
</div>
</div>
<section id="parte-1.-los-datos" class="level2">
<h2 class="anchored" data-anchor-id="parte-1.-los-datos">Parte 1. Los datos</h2>
<section id="qué-es-un-dataset" class="level3">
<h3 class="anchored" data-anchor-id="qué-es-un-dataset">¿Qué es un dataset?</h3>
<p><strong>Qué es:</strong> un conjunto de datos organizado, casi siempre en forma de tabla. Cada fila es un caso (una persona, una venta, una transacción) y cada columna es una característica de ese caso.</p>
<p><strong>Ejemplo:</strong> una tabla de clientes de un banco, donde cada fila es un cliente y las columnas son edad, ingresos, ciudad y si pagó o no su crédito.</p>
<p><strong>Por qué importa:</strong> casi todo en análisis de datos y Machine Learning empieza con una tabla así. Entender qué representa cada fila es la primera pregunta que debes hacerte.</p>
</section>
<section id="observación-y-variable" class="level3">
<h3 class="anchored" data-anchor-id="observación-y-variable">Observación y variable</h3>
<ul>
<li><strong>Observación (fila, registro, muestra):</strong> cada caso individual del dataset.</li>
<li><strong>Variable (columna, atributo):</strong> cada característica que mides de esos casos.</li>
</ul>
<p>Si tienes 1.000 clientes y 8 columnas, tienes 1.000 observaciones y 8 variables.</p>
</section>
<section id="tipos-de-variables" class="level3">
<h3 class="anchored" data-anchor-id="tipos-de-variables">Tipos de variables</h3>
<p><strong>Qué es:</strong> no todas las columnas son iguales, y el tipo decide qué puedes hacer con ellas.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Tipo</th>
<th>Qué representa</th>
<th>Ejemplo</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Numérica continua</td>
<td>Una medida que puede tomar cualquier valor</td>
<td>Ingresos, temperatura, peso</td>
</tr>
<tr class="even">
<td>Numérica discreta</td>
<td>Un conteo</td>
<td>Número de hijos, compras al mes</td>
</tr>
<tr class="odd">
<td>Categórica nominal</td>
<td>Grupos sin orden</td>
<td>Ciudad, color, tipo de producto</td>
</tr>
<tr class="even">
<td>Categórica ordinal</td>
<td>Grupos con un orden</td>
<td>Nivel educativo, talla S/M/L</td>
</tr>
<tr class="odd">
<td>Fecha y hora</td>
<td>Un momento en el tiempo</td>
<td>Fecha de compra</td>
</tr>
<tr class="even">
<td>Texto</td>
<td>Lenguaje libre</td>
<td>Comentarios de clientes</td>
</tr>
</tbody>
</table>
<p><strong>Por qué importa:</strong> no puedes sacar el promedio de una ciudad, y un modelo no entiende la palabra “Medellín” a menos que la conviertas en números. Saber el tipo de cada variable evita errores silenciosos.</p>
</section>
<section id="datos-estructurados-y-no-estructurados" class="level3">
<h3 class="anchored" data-anchor-id="datos-estructurados-y-no-estructurados">Datos estructurados y no estructurados</h3>
<ul>
<li><strong>Estructurados:</strong> datos en tablas con columnas definidas (una hoja de cálculo, una base de datos <a href="https://es.wikipedia.org/wiki/SQL">SQL</a>).</li>
<li><strong>No estructurados:</strong> texto, imágenes, audio, video. No vienen en filas y columnas.</li>
</ul>
<p>Este blog empieza por los estructurados, que es donde vive la mayoría del trabajo en empresas.</p>
</section>
</section>
<section id="parte-2.-análisis-de-datos" class="level2">
<h2 class="anchored" data-anchor-id="parte-2.-análisis-de-datos">Parte 2. Análisis de datos</h2>
<section id="qué-es-el-análisis-de-datos" class="level3">
<h3 class="anchored" data-anchor-id="qué-es-el-análisis-de-datos">¿Qué es el análisis de datos?</h3>
<p><strong>Qué es:</strong> el proceso de inspeccionar, limpiar, transformar y resumir datos para responder preguntas y tomar decisiones.</p>
<p><strong>Ejemplo:</strong> “¿En qué meses vendemos más?” o “¿Qué clientes tienen más probabilidad de dejar de comprar?”.</p>
<p><strong>Por qué importa:</strong> antes de cualquier modelo de Machine Learning hay un análisis. Muchas preguntas de negocio se responden con un buen análisis, sin necesidad de un modelo.</p>
</section>
<section id="análisis-exploratorio-de-datos-eda" class="level3">
<h3 class="anchored" data-anchor-id="análisis-exploratorio-de-datos-eda">Análisis exploratorio de datos (EDA)</h3>
<p><strong>Qué es:</strong> el primer contacto serio con un dataset. Revisas su tamaño, tipos de variables, valores faltantes, distribuciones y relaciones entre columnas.</p>
<p><strong>Por qué importa:</strong> es donde descubres los problemas antes de que te exploten en la cara. Un modelo entrenado sobre datos que no entiendes es una caja negra encima de otra caja negra.</p>
</section>
<section id="estadística-descriptiva" class="level3">
<h3 class="anchored" data-anchor-id="estadística-descriptiva">Estadística descriptiva</h3>
<p>Son los números que resumen una variable:</p>
<ul>
<li><strong>Media (promedio):</strong> la suma de los valores dividida entre la cantidad. Sensible a valores extremos.</li>
<li><strong>Mediana:</strong> el valor del medio cuando ordenas los datos. Más robusta ante extremos.</li>
<li><strong>Moda:</strong> el valor que más se repite.</li>
<li><strong>Desviación estándar:</strong> qué tan dispersos están los valores alrededor de la media.</li>
<li><strong>Percentiles y cuartiles:</strong> el percentil 90 es el valor por debajo del cual está el 90% de los datos.</li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Nota</span>Media vs.&nbsp;mediana en la vida real
</div>
</div>
<div class="callout-body-container callout-body">
<p>Si en una sala hay 9 personas que ganan 2 millones y entra alguien que gana 200 millones, la media se dispara a casi 22 millones. La mediana sigue en 2 millones. Por eso los ingresos casi siempre se reportan con la mediana.</p>
</div>
</div>
<p>Así se ve en una distribución real de ingresos, donde unos pocos valores muy altos jalan la media hacia la derecha:</p>
<div id="217fb54d" class="cell" data-execution_count="2">
<details class="code-fold">
<summary>Ver el código del gráfico</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">ingresos <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rng.lognormal(mean<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># millones</span></span>
<span id="cb1-2"></span>
<span id="cb1-3">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb1-4">ax.hist(ingresos, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>TEAL, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>)</span>
<span id="cb1-5">ax.axvline(np.median(ingresos), color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DARK, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Mediana: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>np<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>median(ingresos)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.1f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> M"</span>)</span>
<span id="cb1-6">ax.axvline(ingresos.mean(), color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>CORAL, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ls<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"--"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Media: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>ingresos<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>mean()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.1f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> M"</span>)</span>
<span id="cb1-7">ax.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Ingreso mensual (millones)"</span>, ylabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Número de personas"</span>,</span>
<span id="cb1-8">       title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Media vs. mediana en datos asimétricos"</span>)</span>
<span id="cb1-9">ax.legend(frameon<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb1-10">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/index_files/figure-html/cell-3-output-1.png" alt="Histograma de ingresos con cola hacia la derecha, con la mediana marcada más a la izquierda que la media" width="771" height="436" class="figure-img"></p>
<figcaption>En datos con cola larga, la media se aleja de la mayoría de los casos; la mediana no.</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="distribución" class="level3">
<h3 class="anchored" data-anchor-id="distribución">Distribución</h3>
<p><strong>Qué es:</strong> la forma en que se reparten los valores de una variable. Se ve con un histograma.</p>
<p><strong>Por qué importa:</strong> te dice si los datos están concentrados, si tienen cola larga hacia un lado (asimetría) o si hay grupos separados. Muchas técnicas asumen ciertas formas de distribución.</p>
</section>
<section id="valores-faltantes" class="level3">
<h3 class="anchored" data-anchor-id="valores-faltantes">Valores faltantes</h3>
<p><strong>Qué es:</strong> celdas vacías en tu tabla (<code>NaN</code>, <code>null</code>, <code>None</code>).</p>
<p><strong>Por qué importa:</strong> la mayoría de modelos no aceptan valores faltantes. Además, <em>por qué</em> falta un dato a veces es información en sí misma. Puedes eliminarlos, rellenarlos (imputar) o marcarlos, pero la decisión depende del contexto. La <a href="https://pandas.pydata.org/docs/user_guide/missing_data.html">guía de datos faltantes de pandas</a> explica cómo detectarlos y tratarlos.</p>
</section>
<section id="outliers-valores-atípicos" class="level3">
<h3 class="anchored" data-anchor-id="outliers-valores-atípicos">Outliers (valores atípicos)</h3>
<p><strong>Qué es:</strong> valores muy alejados del resto.</p>
<p><strong>Por qué importa:</strong> a veces son errores (una edad de 250 años), a veces son lo más interesante del dataset (una transacción fraudulenta). Nunca los borres sin entender qué son.</p>
<p>El diagrama de caja (boxplot) es la forma más rápida de verlos: los puntos sueltos fuera de los “bigotes” son candidatos a outlier.</p>
<div id="7ac2c829" class="cell" data-execution_count="3">
<details class="code-fold">
<summary>Ver el código del gráfico</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">montos <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.concatenate([rng.normal(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>), [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">380</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">410</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">455</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">520</span>]])</span>
<span id="cb2-2"></span>
<span id="cb2-3">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.6</span>))</span>
<span id="cb2-4">ax.boxplot(montos, vert<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, widths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, patch_artist<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb2-5">           boxprops<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>(facecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#ccfbf1"</span>, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>TEAL),</span>
<span id="cb2-6">           medianprops<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>(color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DARK, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb2-7">           flierprops<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>(marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"o"</span>, markerfacecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>CORAL, markeredgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>CORAL))</span>
<span id="cb2-8">ax.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Monto de la transacción (USD)"</span>, yticks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[], title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Detectar outliers con un boxplot"</span>)</span>
<span id="cb2-9">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/index_files/figure-html/cell-4-output-1.png" alt="Diagrama de caja de montos de transacciones con varios puntos atípicos muy por encima del resto" width="704" height="317" class="figure-img"></p>
<figcaption>Los puntos fuera de los bigotes son posibles outliers. Hay que investigarlos antes de decidir qué hacer.</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="correlación" class="level3">
<h3 class="anchored" data-anchor-id="correlación">Correlación</h3>
<p><strong>Qué es:</strong> una medida de qué tanto se mueven juntas dos variables numéricas. Va de -1 a 1.</p>
<ul>
<li>Cerca de <strong>1</strong>: cuando una sube, la otra también.</li>
<li>Cerca de <strong>-1</strong>: cuando una sube, la otra baja.</li>
<li>Cerca de <strong>0</strong>: no hay relación lineal.</li>
</ul>
<div id="11c78310" class="cell" data-execution_count="4">
<details class="code-fold">
<summary>Ver el código del gráfico</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rng.normal(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>)</span>
<span id="cb3-2">casos <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb3-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Positiva"</span>: x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> rng.normal(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>),</span>
<span id="cb3-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Negativa"</span>: <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> rng.normal(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>),</span>
<span id="cb3-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sin relación"</span>: rng.normal(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>),</span>
<span id="cb3-6">}</span>
<span id="cb3-7">fig, axes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.2</span>), sharey<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb3-8"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ax, (nombre, y_) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(axes, casos.items()):</span>
<span id="cb3-9">    r <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.corrcoef(x, y_)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb3-10">    ax.scatter(x, y_, s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>TEAL, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>)</span>
<span id="cb3-11">    ax.set_title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>nombre<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> (r = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">)"</span>)</span>
<span id="cb3-12">    ax.set_xticks([])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_yticks([])</span>
<span id="cb3-13">plt.tight_layout()</span>
<span id="cb3-14">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/index_files/figure-html/cell-5-output-1.png" alt="Tres diagramas de dispersión: correlación positiva, negativa y sin correlación" width="1085" height="337" class="figure-img"></p>
<figcaption>Tres tipos de correlación entre dos variables numéricas.</figcaption>
</figure>
</div>
</div>
</div>
<div class="callout callout-style-default callout-warning callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Advertencia</span>Correlación no es causalidad
</div>
</div>
<div class="callout-body-container callout-body">
<p>Las ventas de helado y los ahogamientos están correlacionados. No porque el helado cause ahogamientos, sino porque ambos suben en verano. Una correlación te da una pista, nunca una conclusión. A esta falacia se le conoce como <a href="https://es.wikipedia.org/wiki/Cum_hoc_ergo_propter_hoc"><em>cum hoc ergo propter hoc</em></a>.</p>
</div>
</div>
</section>
<section id="limpieza-de-datos" class="level3">
<h3 class="anchored" data-anchor-id="limpieza-de-datos">Limpieza de datos</h3>
<p><strong>Qué es:</strong> corregir o eliminar lo que está mal: duplicados, formatos inconsistentes (“Bogotá”, “bogota”, “BOGOTA”), tipos incorrectos, valores imposibles.</p>
<p><strong>Por qué importa:</strong> la regla clásica es <em>garbage in, garbage out</em>. Si entra basura, sale basura, sin importar qué tan sofisticado sea el modelo.</p>
</section>
<section id="visualización-de-datos" class="level3">
<h3 class="anchored" data-anchor-id="visualización-de-datos">Visualización de datos</h3>
<p><strong>Qué es:</strong> representar los datos en gráficos para entenderlos o comunicarlos. En Python las librerías más usadas son <a href="https://matplotlib.org/">Matplotlib</a> y <a href="https://seaborn.pydata.org/">seaborn</a>. Los básicos:</p>
<ul>
<li><strong>Histograma:</strong> distribución de una variable numérica.</li>
<li><strong>Diagrama de caja (boxplot):</strong> mediana, cuartiles y outliers.</li>
<li><strong>Diagrama de dispersión (scatter):</strong> relación entre dos variables numéricas.</li>
<li><strong>Gráfico de barras:</strong> comparar categorías.</li>
<li><strong>Gráfico de líneas:</strong> evolución en el tiempo.</li>
</ul>
</section>
</section>
<section id="parte-3.-machine-learning" class="level2">
<h2 class="anchored" data-anchor-id="parte-3.-machine-learning">Parte 3. Machine Learning</h2>
<section id="qué-es-machine-learning" class="level3">
<h3 class="anchored" data-anchor-id="qué-es-machine-learning">¿Qué es Machine Learning?</h3>
<p><strong>Qué es:</strong> una rama de la inteligencia artificial donde, en lugar de programar reglas a mano, le das ejemplos a un algoritmo y él aprende los patrones por sí mismo.</p>
<p><strong>Ejemplo:</strong> en vez de escribir reglas para detectar spam (“si dice <em>gratis</em> y tiene más de 3 enlaces…”), le das miles de correos marcados como spam o no spam y el modelo aprende a distinguirlos.</p>
<p><strong>Por qué importa:</strong> permite resolver problemas donde las reglas son demasiadas o demasiado sutiles para escribirlas a mano.</p>
</section>
<section id="inteligencia-artificial-machine-learning-y-deep-learning" class="level3">
<h3 class="anchored" data-anchor-id="inteligencia-artificial-machine-learning-y-deep-learning">Inteligencia artificial, Machine Learning y Deep Learning</h3>
<p>Son círculos uno dentro del otro:</p>
<ul>
<li><strong>Inteligencia artificial (IA):</strong> el campo general de hacer que las máquinas realicen tareas que asociamos con inteligencia.</li>
<li><strong>Machine Learning (ML):</strong> la parte de la IA que aprende a partir de datos.</li>
<li><strong>Deep Learning:</strong> la parte del ML que usa redes neuronales con muchas capas. Es lo que está detrás del reconocimiento de imágenes y de los modelos de lenguaje como los chatbots.</li>
</ul>
</section>
<section id="modelo" class="level3">
<h3 class="anchored" data-anchor-id="modelo">Modelo</h3>
<p><strong>Qué es:</strong> el resultado de entrenar un algoritmo con datos. Es una función que recibe información de entrada y devuelve una predicción.</p>
<p><strong>Ejemplo:</strong> un modelo que recibe metros cuadrados, barrio y número de habitaciones, y devuelve un precio estimado de la vivienda.</p>
</section>
<section id="features-y-target" class="level3">
<h3 class="anchored" data-anchor-id="features-y-target">Features y target</h3>
<ul>
<li><strong>Features (variables predictoras, X):</strong> la información que el modelo usa para predecir.</li>
<li><strong>Target (variable objetivo, y):</strong> lo que quieres predecir.</li>
</ul>
<p>En el ejemplo de la vivienda, los metros cuadrados y el barrio son <em>features</em>. El precio es el <em>target</em>.</p>
</section>
<section id="entrenamiento" class="level3">
<h3 class="anchored" data-anchor-id="entrenamiento">Entrenamiento</h3>
<p><strong>Qué es:</strong> el proceso en el que el algoritmo ajusta sus parámetros internos mirando ejemplos, para que sus predicciones se parezcan lo más posible a las respuestas reales. En Python suele ser una sola línea: <code>modelo.fit(X, y)</code>.</p>
</section>
<section id="tipos-de-aprendizaje" class="level3">
<h3 class="anchored" data-anchor-id="tipos-de-aprendizaje">Tipos de aprendizaje</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Tipo</th>
<th>Idea</th>
<th>Ejemplo</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Supervisado</strong></td>
<td>Aprende de ejemplos con la respuesta correcta</td>
<td>Predecir si un cliente pagará su crédito</td>
</tr>
<tr class="even">
<td><strong>No supervisado</strong></td>
<td>Busca patrones sin respuestas previas</td>
<td>Agrupar clientes con hábitos parecidos</td>
</tr>
<tr class="odd">
<td><strong>Por refuerzo</strong></td>
<td>Aprende por prueba y error, con premios y castigos</td>
<td>Un agente que aprende a jugar un videojuego</td>
</tr>
</tbody>
</table>
</section>
<section id="clasificación-y-regresión" class="level3">
<h3 class="anchored" data-anchor-id="clasificación-y-regresión">Clasificación y regresión</h3>
<p>Son los dos grandes tipos de problemas supervisados:</p>
<ul>
<li><strong>Clasificación:</strong> el target es una categoría. ¿Spam o no spam? ¿Fraude o no fraude?</li>
<li><strong>Regresión:</strong> el target es un número. ¿Cuánto costará esta casa? ¿Cuántas unidades venderemos?</li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Nota</span>Ojo con el nombre
</div>
</div>
<div class="callout-body-container callout-body">
<p>La <em>regresión logística</em>, a pesar del nombre, se usa para <strong>clasificación</strong>. Es una de esas trampas de vocabulario que confunden a todos al principio.</p>
</div>
</div>
</section>
<section id="clustering-agrupamiento" class="level3">
<h3 class="anchored" data-anchor-id="clustering-agrupamiento">Clustering (agrupamiento)</h3>
<p><strong>Qué es:</strong> una técnica no supervisada que agrupa observaciones parecidas sin saber de antemano a qué grupo pertenecen.</p>
<p><strong>Ejemplo:</strong> segmentar clientes en grupos según su comportamiento de compra para diseñar campañas diferentes.</p>
<div id="b4243878" class="cell" data-execution_count="5">
<details class="code-fold">
<summary>Ver el código del gráfico</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_blobs</span>
<span id="cb4-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.cluster <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> KMeans</span>
<span id="cb4-3"></span>
<span id="cb4-4">Xc, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_blobs(n_samples<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>, centers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, cluster_std<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>)</span>
<span id="cb4-5">grupos <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> KMeans(n_clusters<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, n_init<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>).fit_predict(Xc)</span>
<span id="cb4-6"></span>
<span id="cb4-7">fig, axes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.6</span>), sharex<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, sharey<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb4-8">axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].scatter(Xc[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], Xc[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>GRAY)</span>
<span id="cb4-9">axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Antes: clientes sin etiqueta"</span>)</span>
<span id="cb4-10">axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].scatter(Xc[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], Xc[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>, c<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[[TEAL, CORAL, DARK][g] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> g <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> grupos])</span>
<span id="cb4-11">axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Después: 3 grupos encontrados"</span>)</span>
<span id="cb4-12"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ax <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> axes:</span>
<span id="cb4-13">    ax.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Frecuencia de compra"</span>, ylabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Ticket promedio"</span>, xticks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[], yticks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[])</span>
<span id="cb4-14">plt.tight_layout()</span>
<span id="cb4-15">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/index_files/figure-html/cell-6-output-1.png" alt="Dos diagramas de dispersión: a la izquierda clientes sin agrupar, a la derecha los mismos clientes coloreados en tres grupos" width="975" height="381" class="figure-img"></p>
<figcaption>K-Means encuentra grupos en los datos sin que nadie le diga cuáles son.</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="algoritmos-comunes-para-empezar" class="level3">
<h3 class="anchored" data-anchor-id="algoritmos-comunes-para-empezar">Algoritmos comunes para empezar</h3>
<ul>
<li><strong>Regresión lineal:</strong> traza la línea que mejor se ajusta a los datos. Base de la regresión.</li>
<li><strong>Regresión logística:</strong> estima la probabilidad de que algo pertenezca a una clase.</li>
<li><strong>Árbol de decisión:</strong> una secuencia de preguntas sí/no. Fácil de interpretar.</li>
<li><strong>Random Forest:</strong> muchos árboles que votan. Más preciso y estable que uno solo.</li>
<li><strong>Gradient Boosting (<a href="https://xgboost.readthedocs.io/en/stable/">XGBoost</a>, <a href="https://lightgbm.readthedocs.io/en/stable/">LightGBM</a>):</strong> árboles que se corrigen unos a otros. Muy fuertes en datos tabulares.</li>
<li><strong>K-Means:</strong> el <a href="https://scikit-learn.org/stable/modules/clustering.html">algoritmo de clustering</a> más conocido.</li>
<li><strong>Redes neuronales:</strong> capas de operaciones que aprenden patrones complejos. La librería más popular para construirlas es <a href="https://pytorch.org/">PyTorch</a>.</li>
</ul>
</section>
</section>
<section id="parte-4.-evaluar-un-modelo" class="level2">
<h2 class="anchored" data-anchor-id="parte-4.-evaluar-un-modelo">Parte 4. Evaluar un modelo</h2>
<section id="train-validation-y-test" class="level3">
<h3 class="anchored" data-anchor-id="train-validation-y-test">Train, validation y test</h3>
<p><strong>Qué es:</strong> dividir los datos en partes con funciones distintas.</p>
<ul>
<li><strong>Entrenamiento (train):</strong> el modelo aprende de aquí.</li>
<li><strong>Validación:</strong> se usa para ajustar y comparar modelos.</li>
<li><strong>Prueba (test):</strong> se usa una sola vez, al final, para medir el rendimiento real.</li>
</ul>
<p><strong>Por qué importa:</strong> si evalúas un modelo con los mismos datos con los que aprendió, es como darle a un estudiante el examen con las respuestas. Va a sacar 5, pero no aprendió nada.</p>
</section>
<section id="overfitting-y-underfitting" class="level3">
<h3 class="anchored" data-anchor-id="overfitting-y-underfitting">Overfitting y underfitting</h3>
<ul>
<li><strong>Overfitting (sobreajuste):</strong> el modelo memorizó los datos de entrenamiento, incluido el ruido. Le va excelente en train y mal con datos nuevos.</li>
<li><strong>Underfitting (subajuste):</strong> el modelo es demasiado simple y no capta ni siquiera los patrones básicos. Le va mal en todo.</li>
</ul>
<p>El objetivo es el punto medio: un modelo que <strong>generaliza</strong>, es decir, que funciona bien con datos que nunca vio.</p>
<div id="de4608de" class="cell" data-execution_count="6">
<details class="code-fold">
<summary>Ver el código del gráfico</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> numpy.polynomial <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Polynomial</span>
<span id="cb5-2"></span>
<span id="cb5-3">xs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sort(rng.uniform(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>))</span>
<span id="cb5-4">ys <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sin(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.pi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> xs) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> rng.normal(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>)</span>
<span id="cb5-5">grid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>)</span>
<span id="cb5-6"></span>
<span id="cb5-7">fig, axes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.2</span>), sharey<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb5-8"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ax, grado, titulo <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(axes, [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>],</span>
<span id="cb5-9">                             [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Underfitting"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Buen ajuste"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Overfitting"</span>]):</span>
<span id="cb5-10">    curva <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Polynomial.fit(xs, ys, grado)</span>
<span id="cb5-11">    ax.scatter(xs, ys, s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DARK, zorder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb5-12">    ax.plot(grid, curva(grid), color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>CORAL <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> grado <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> TEAL, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb5-13">    ax.set_title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>titulo<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> (grado </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>grado<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">)"</span>)</span>
<span id="cb5-14">    ax.set_ylim(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_xticks([])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_yticks([])</span>
<span id="cb5-15">plt.tight_layout()</span>
<span id="cb5-16">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/index_files/figure-html/cell-7-output-1.png" alt="Tres gráficos con los mismos puntos y curvas de ajuste: una línea recta que no capta la forma, una curva suave que sí, y una curva muy ondulada que pasa por cada punto" width="1085" height="337" class="figure-img"></p>
<figcaption>Mismo dataset, tres modelos: demasiado simple, adecuado y demasiado complejo.</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="validación-cruzada" class="level3">
<h3 class="anchored" data-anchor-id="validación-cruzada">Validación cruzada</h3>
<p><strong>Qué es:</strong> en lugar de una sola división train/test, divides los datos en <em>k</em> partes (por ejemplo 5), entrenas 5 veces dejando una parte distinta para evaluar cada vez, y promedias los resultados.</p>
<p><strong>Por qué importa:</strong> te da una estimación más confiable y te muestra si el rendimiento es <strong>estable</strong> o si depende de la suerte de cómo partiste los datos. La <a href="https://scikit-learn.org/stable/modules/cross_validation.html">documentación de scikit-learn sobre validación cruzada</a> lo explica con diagramas muy claros.</p>
</section>
<section id="métricas-de-clasificación" class="level3">
<h3 class="anchored" data-anchor-id="métricas-de-clasificación">Métricas de clasificación</h3>
<ul>
<li><strong>Accuracy (exactitud):</strong> porcentaje de predicciones correctas. Engañosa cuando las clases están desbalanceadas.</li>
<li><strong>Precision:</strong> de lo que el modelo marcó como positivo, cuánto era realmente positivo.</li>
<li><strong>Recall (sensibilidad):</strong> de todos los positivos reales, cuántos encontró el modelo.</li>
<li><strong>F1-score:</strong> balance entre precision y recall.</li>
<li><strong>Matriz de confusión:</strong> tabla con aciertos y errores por clase.</li>
<li><strong>ROC-AUC:</strong> qué tan bien separa el modelo las clases en todos los umbrales posibles. 0,5 es azar, 1 es perfecto.</li>
</ul>
<div class="callout callout-style-default callout-warning callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Advertencia</span>La trampa del 99% de accuracy
</div>
</div>
<div class="callout-body-container callout-body">
<p>Si solo el 1% de las transacciones son fraude, un modelo que siempre dice “no es fraude” tiene 99% de accuracy y no sirve para nada. Por eso en problemas desbalanceados se miran precision, recall y PR-AUC.</p>
</div>
</div>
<p>Todas estas métricas están implementadas en el <a href="https://scikit-learn.org/stable/modules/model_evaluation.html">módulo de métricas de scikit-learn</a>.</p>
</section>
<section id="métricas-de-regresión" class="level3">
<h3 class="anchored" data-anchor-id="métricas-de-regresión">Métricas de regresión</h3>
<ul>
<li><strong>MAE (error absoluto medio):</strong> en promedio, por cuánto se equivoca el modelo. Fácil de explicar.</li>
<li><strong>RMSE (raíz del error cuadrático medio):</strong> parecido, pero castiga más los errores grandes.</li>
<li><strong>R² (coeficiente de determinación):</strong> qué proporción de la variación del target explica el modelo.</li>
</ul>
</section>
<section id="sesgo-y-varianza" class="level3">
<h3 class="anchored" data-anchor-id="sesgo-y-varianza">Sesgo y varianza</h3>
<ul>
<li><strong>Sesgo:</strong> error por suposiciones demasiado simples (lleva al underfitting).</li>
<li><strong>Varianza:</strong> error por ser demasiado sensible a los datos de entrenamiento (lleva al overfitting).</li>
</ul>
<p>Mejorar uno suele empeorar el otro. A eso se le llama el <strong>trade-off sesgo-varianza</strong>.</p>
</section>
<section id="data-leakage-fuga-de-datos" class="level3">
<h3 class="anchored" data-anchor-id="data-leakage-fuga-de-datos">Data leakage (fuga de datos)</h3>
<p><strong>Qué es:</strong> cuando información que no tendrías en el momento real de la predicción se cuela en el entrenamiento.</p>
<p><strong>Ejemplo:</strong> predecir si un cliente abandonará el servicio usando una columna “fecha de cancelación”. El modelo parece perfecto, pero en la vida real esa columna no existe hasta que el cliente ya se fue.</p>
<p><strong>Por qué importa:</strong> es una de las causas más comunes de modelos que brillan en el notebook y fracasan en producción. scikit-learn tiene una sección dedicada a <a href="https://scikit-learn.org/stable/common_pitfalls.html">errores comunes y buenas prácticas</a> que vale la pena leer.</p>
</section>
</section>
<section id="parte-5.-preparar-los-datos-para-un-modelo" class="level2">
<h2 class="anchored" data-anchor-id="parte-5.-preparar-los-datos-para-un-modelo">Parte 5. Preparar los datos para un modelo</h2>
<section id="feature-engineering" class="level3">
<h3 class="anchored" data-anchor-id="feature-engineering">Feature engineering</h3>
<p><strong>Qué es:</strong> crear o transformar variables para que el modelo aprenda mejor.</p>
<p><strong>Ejemplo:</strong> a partir de “fecha de compra” crear “día de la semana” o “días desde la última compra”.</p>
</section>
<section id="encoding-de-variables-categóricas" class="level3">
<h3 class="anchored" data-anchor-id="encoding-de-variables-categóricas">Encoding de variables categóricas</h3>
<p><strong>Qué es:</strong> convertir texto en números. La técnica más común es <strong><a href="https://scikit-learn.org/stable/modules/preprocessing.html">one-hot encoding</a></strong>: la columna “ciudad” se convierte en varias columnas (ciudad_Medellín, ciudad_Bogotá…) con 1 o 0.</p>
</section>
<section id="escalado-y-normalización" class="level3">
<h3 class="anchored" data-anchor-id="escalado-y-normalización">Escalado y normalización</h3>
<p><strong>Qué es:</strong> poner las variables numéricas en rangos comparables. Si una columna va de 0 a 1 y otra de 0 a 10 millones, algunos algoritmos le darán más peso a la segunda solo por su tamaño.</p>
</section>
<section id="pipeline" class="level3">
<h3 class="anchored" data-anchor-id="pipeline">Pipeline</h3>
<p><strong>Qué es:</strong> una cadena de pasos (limpieza, encoding, escalado, modelo) que se ejecutan siempre en el mismo orden.</p>
<p><strong>Por qué importa:</strong> hace tu trabajo reproducible y ayuda a evitar data leakage, porque cada transformación se aprende solo con los datos de entrenamiento. En scikit-learn se construyen con <a href="https://scikit-learn.org/stable/modules/compose.html"><code>Pipeline</code></a>.</p>
</section>
<section id="hiperparámetros" class="level3">
<h3 class="anchored" data-anchor-id="hiperparámetros">Hiperparámetros</h3>
<p><strong>Qué es:</strong> configuraciones del modelo que tú eliges antes de entrenar, no que el modelo aprende. Por ejemplo, la profundidad máxima de un árbol.</p>
<p><strong>Por qué importa:</strong> cambiarlos puede llevar a un modelo de underfitting a overfitting. Se ajustan usando validación cruzada, por ejemplo con <a href="https://scikit-learn.org/stable/modules/grid_search.html">búsqueda en malla (grid search)</a>.</p>
</section>
</section>
<section id="parte-6.-más-allá-de-la-precisión" class="level2">
<h2 class="anchored" data-anchor-id="parte-6.-más-allá-de-la-precisión">Parte 6. Más allá de la precisión</h2>
<p>Muchos usan estas dos palabras como sinónimos, pero <strong>no son lo mismo</strong>, y confundirlas lleva a malas decisiones. La diferencia está en <em>de dónde sale el entendimiento</em>: del modelo mismo o de una herramienta externa que intenta describirlo.</p>
<section id="interpretabilidad" class="level3">
<h3 class="anchored" data-anchor-id="interpretabilidad">Interpretabilidad</h3>
<p><strong>Qué es:</strong> la propiedad de un modelo cuyo funcionamiento interno una persona puede entender directamente, sin herramientas adicionales. Mirando el modelo ves <em>cómo</em> decide.</p>
<p><strong>Ejemplo:</strong> en una regresión logística cada variable tiene un coeficiente. Si el coeficiente de “días de mora” es positivo y grande, sabes que más días de mora aumentan el riesgo, y sabes cuánto. Un árbol de decisión pequeño también es interpretable: puedes seguir las preguntas sí/no de principio a fin.</p>
<p><strong>Por qué importa:</strong> la explicación <em>es</em> el modelo. No hay una capa intermedia que pueda equivocarse.</p>
</section>
<section id="explicabilidad" class="level3">
<h3 class="anchored" data-anchor-id="explicabilidad">Explicabilidad</h3>
<p><strong>Qué es:</strong> la capacidad de dar una explicación sobre las decisiones de un modelo que, por sí mismo, no se entiende (una “caja negra” como un Random Forest, XGBoost o una red neuronal). La explicación la produce <strong>otra herramienta, después de entrenar</strong> el modelo (por eso se le llama explicación <em>post-hoc</em>).</p>
<p><strong>Ejemplo:</strong> técnicas como <a href="https://shap.readthedocs.io/en/latest/">SHAP</a>, <a href="https://github.com/marcotcr/lime">LIME</a>, la <a href="https://scikit-learn.org/stable/modules/permutation_importance.html">importancia por permutación</a> o los <a href="https://scikit-learn.org/stable/modules/partial_dependence.html">gráficos de dependencia parcial</a> miran cómo cambian las predicciones cuando cambian las entradas y, a partir de eso, estiman qué variables pesaron más.</p>
<p><strong>Por qué importa:</strong> permite usar modelos más complejos y poderosos sin renunciar del todo a entenderlos. Pero hay que tener claro que la explicación es una <strong>aproximación</strong> del comportamiento del modelo, no el modelo.</p>
</section>
<section id="interpretabilidad-vs-explicabilidad" class="level3">
<h3 class="anchored" data-anchor-id="interpretabilidad-vs-explicabilidad">Interpretabilidad vs.&nbsp;explicabilidad: por qué no son lo mismo</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th></th>
<th>Interpretabilidad</th>
<th>Explicabilidad</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>De dónde sale el entendimiento</td>
<td>Del propio modelo</td>
<td>De una herramienta externa, después de entrenar</td>
</tr>
<tr class="even">
<td>Modelos típicos</td>
<td>Regresión lineal y logística, árboles pequeños, reglas</td>
<td>Random Forest, gradient boosting, redes neuronales</td>
</tr>
<tr class="odd">
<td>Herramientas</td>
<td>Coeficientes, reglas del árbol</td>
<td>SHAP, LIME, importancia por permutación, dependencia parcial</td>
</tr>
<tr class="even">
<td>Qué tan fiel es</td>
<td>Exacta: describe lo que el modelo realmente hace</td>
<td>Aproximada: puede no reflejar del todo al modelo</td>
</tr>
<tr class="odd">
<td>Pregunta que responde</td>
<td>“¿Cómo funciona el modelo?”</td>
<td>“¿Qué influyó en este resultado?”</td>
</tr>
</tbody>
</table>
<p>Hay además dos alcances que aplican a ambas:</p>
<ul>
<li><strong>Global:</strong> cómo se comporta el modelo en general (qué variables importan más en todos los casos).</li>
<li><strong>Local:</strong> por qué tomó <em>una</em> decisión concreta (por qué a <em>este</em> cliente se le negó el crédito).</li>
</ul>
<div class="callout callout-style-default callout-warning callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Advertencia</span>Una explicación puede ser convincente y estar equivocada
</div>
</div>
<div class="callout-body-container callout-body">
<p>Una explicación post-hoc puede verse muy razonable y aun así no reflejar lo que el modelo hace de verdad. Por eso la investigadora Cynthia Rudin propone, en un artículo muy citado, que en <a href="https://www.nature.com/articles/s42256-019-0048-x">decisiones de alto impacto se usen modelos interpretables en lugar de explicar cajas negras</a>. Si un modelo simple e interpretable logra un rendimiento parecido al de uno complejo, casi siempre es la mejor opción.</p>
</div>
</div>
<p>Veámoslo con los mismos datos del ejemplo final. A la izquierda, un modelo <strong>interpretable</strong>: los coeficientes <em>son</em> el modelo. A la derecha, una <strong>explicación</strong> de un Random Forest calculada desde afuera, midiendo cuánto empeora el modelo cuando se desordena cada variable.</p>
<div id="4e659fc1" class="cell" data-execution_count="7">
<details class="code-fold">
<summary>Ver el código del gráfico</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> load_breast_cancer</span>
<span id="cb6-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split</span>
<span id="cb6-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.pipeline <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_pipeline</span>
<span id="cb6-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.preprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> StandardScaler</span>
<span id="cb6-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.linear_model <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LogisticRegression</span>
<span id="cb6-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.ensemble <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> RandomForestClassifier</span>
<span id="cb6-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.inspection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> permutation_importance</span>
<span id="cb6-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb6-9"></span>
<span id="cb6-10">cancer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> load_breast_cancer(as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb6-11">Xa, Xb, ya, yb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(cancer.data, cancer.target, test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>,</span>
<span id="cb6-12">                                  stratify<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cancer.target, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb6-13"></span>
<span id="cb6-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Interpretable: regresión logística sobre datos escalados</span></span>
<span id="cb6-15">logit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_pipeline(StandardScaler(), LogisticRegression(max_iter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>)).fit(Xa, ya)</span>
<span id="cb6-16">coefs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.Series(logit[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].coef_[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Xa.columns)</span>
<span id="cb6-17">coefs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> coefs.reindex(coefs.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>().sort_values().index)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>:]</span>
<span id="cb6-18"></span>
<span id="cb6-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Caja negra + explicación post-hoc: Random Forest + importancia por permutación</span></span>
<span id="cb6-20">bosque <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RandomForestClassifier(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>).fit(Xa, ya)</span>
<span id="cb6-21">perm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> permutation_importance(bosque, Xb, yb, n_repeats<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb6-22">imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.Series(perm.importances_mean, index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Xa.columns).sort_values()[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>:]</span>
<span id="cb6-23"></span>
<span id="cb6-24">fig, axes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.2</span>))</span>
<span id="cb6-25">axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].barh(coefs.index, coefs.values,</span>
<span id="cb6-26">             color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[CORAL <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> TEAL <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> v <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> coefs.values])</span>
<span id="cb6-27">axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].axvline(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>GRAY, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb6-28">axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Interpretable: coeficientes"</span>, xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Peso en el modelo (negativo = más riesgo de maligno)"</span>)</span>
<span id="cb6-29">axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].barh(imp.index, imp.values, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>TEAL)</span>
<span id="cb6-30">axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Explicación post-hoc: Random Forest"</span>, xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Caída en accuracy al desordenar la variable"</span>)</span>
<span id="cb6-31">plt.tight_layout()</span>
<span id="cb6-32">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/index_files/figure-html/cell-8-output-1.png" alt="Dos gráficos de barras horizontales: los coeficientes de una regresión logística y la importancia por permutación de un Random Forest, para las ocho variables más relevantes de cada uno" width="1217" height="447" class="figure-img"></p>
<figcaption>Izquierda: interpretabilidad (los coeficientes del modelo). Derecha: explicabilidad (importancia por permutación calculada después de entrenar una caja negra).</figcaption>
</figure>
</div>
</div>
</div>
<p>Fíjate en que los dos modelos no destacan exactamente las mismas variables. No es un error: son preguntas distintas respondidas con herramientas distintas. Los coeficientes te dicen cómo decide la regresión logística. La importancia por permutación te dice de qué variables <em>depende</em> el Random Forest para acertar, pero no cómo las combina por dentro.</p>
<p><strong>Por qué todo esto importa:</strong> si un modelo niega un crédito, la persona y el regulador merecen saber por qué. Y no basta con que exista <em>una</em> explicación: hay que saber si viene del modelo mismo o si es una aproximación, y evaluar qué tan confiable es. Si quieres profundizar, el libro gratuito <a href="https://christophm.github.io/interpretable-ml-book/"><em>Interpretable Machine Learning</em></a> de Christoph Molnar es la referencia más completa.</p>
</section>
<section id="sesgo-algorítmico" class="level3">
<h3 class="anchored" data-anchor-id="sesgo-algorítmico">Sesgo algorítmico</h3>
<p><strong>Qué es:</strong> cuando un modelo trata de forma injusta a ciertos grupos porque aprendió patrones injustos que ya estaban en los datos históricos.</p>
<p><strong>Por qué importa:</strong> un modelo no es neutral por ser matemático. Hereda lo que hay en sus datos.</p>
</section>
<section id="data-drift-cambio-en-los-datos" class="level3">
<h3 class="anchored" data-anchor-id="data-drift-cambio-en-los-datos">Data drift (cambio en los datos)</h3>
<p><strong>Qué es:</strong> cuando los datos del mundo real cambian con el tiempo y dejan de parecerse a los datos con los que entrenaste.</p>
<p><strong>Ejemplo:</strong> un modelo de crédito entrenado antes de la pandemia que empieza a fallar después de ella, porque el comportamiento de pago cambió.</p>
<p><strong>Por qué importa:</strong> un modelo no se entrena una vez y ya. Hay que monitorearlo.</p>
</section>
</section>
<section id="todo-junto-en-python" class="level2">
<h2 class="anchored" data-anchor-id="todo-junto-en-python">Todo junto en Python</h2>
<p>Este ejemplo usa casi todos los conceptos anteriores con un <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html">dataset público</a> que viene incluido en <a href="https://scikit-learn.org/stable/">scikit-learn</a>: datos de tumores de mama, donde el objetivo es clasificar si son malignos o benignos.</p>
<div id="a026e76e" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> load_breast_cancer</span>
<span id="cb7-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split, cross_val_score</span>
<span id="cb7-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.pipeline <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_pipeline</span>
<span id="cb7-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.preprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> StandardScaler</span>
<span id="cb7-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.linear_model <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LogisticRegression</span>
<span id="cb7-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> classification_report, roc_auc_score</span>
<span id="cb7-7"></span>
<span id="cb7-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1. Dataset: features (X) y target (y)</span></span>
<span id="cb7-9">datos <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> load_breast_cancer(as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb7-10">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> datos.data, datos.target</span>
<span id="cb7-11"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Observaciones: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>X<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> | Variables: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>X<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb7-12"></span>
<span id="cb7-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 2. Separar train y test (el test no se toca hasta el final)</span></span>
<span id="cb7-14">X_train, X_test, y_train, y_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(</span>
<span id="cb7-15">    X, y, test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, stratify<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span></span>
<span id="cb7-16">)</span>
<span id="cb7-17"></span>
<span id="cb7-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 3. Pipeline: escalado + modelo de clasificación</span></span>
<span id="cb7-19">modelo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_pipeline(StandardScaler(), LogisticRegression(max_iter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>))</span>
<span id="cb7-20"></span>
<span id="cb7-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 4. Validación cruzada sobre train: ¿el rendimiento es estable?</span></span>
<span id="cb7-22">scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cross_val_score(modelo, X_train, y_train, cv<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, scoring<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"roc_auc"</span>)</span>
<span id="cb7-23"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"ROC-AUC en validación cruzada: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>scores<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>mean()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> ± </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>scores<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>std()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb7-24"></span>
<span id="cb7-25"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 5. Entrenamiento final y evaluación con datos nunca vistos</span></span>
<span id="cb7-26">modelo.fit(X_train, y_train)</span>
<span id="cb7-27">predicciones <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modelo.predict(X_test)</span>
<span id="cb7-28">probabilidades <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modelo.predict_proba(X_test)[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb7-29"></span>
<span id="cb7-30"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"ROC-AUC en test: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>roc_auc_score(y_test, probabilidades)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb7-31"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(classification_report(y_test, predicciones, target_names<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>datos.target_names))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Observaciones: 569 | Variables: 30
ROC-AUC en validación cruzada: 0.993 ± 0.011
ROC-AUC en test: 0.995
              precision    recall  f1-score   support

   malignant       0.98      0.98      0.98        42
      benign       0.99      0.99      0.99        72

    accuracy                           0.98       114
   macro avg       0.98      0.98      0.98       114
weighted avg       0.98      0.98      0.98       114
</code></pre>
</div>
</div>
<p>Y la matriz de confusión, para ver exactamente en qué se equivocó el modelo:</p>
<div id="2f82594c" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ConfusionMatrixDisplay</span>
<span id="cb9-2"></span>
<span id="cb9-3">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb9-4">ConfusionMatrixDisplay.from_predictions(</span>
<span id="cb9-5">    y_test, predicciones, display_labels<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Maligno"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Benigno"</span>],</span>
<span id="cb9-6">    cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Greens"</span>, colorbar<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax,</span>
<span id="cb9-7">)</span>
<span id="cb9-8">ax.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Predicción del modelo"</span>, ylabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Valor real"</span>, title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Matriz de confusión"</span>)</span>
<span id="cb9-9">plt.show()</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/index_files/figure-html/cell-10-output-1.png" alt="Matriz de confusión de 2 por 2 con los aciertos y errores del modelo para tumores malignos y benignos" width="464" height="437" class="figure-img"></p>
<figcaption>Matriz de confusión del modelo sobre el conjunto de prueba.</figcaption>
</figure>
</div>
</div>
</div>
<p>Lo que acabas de ver, en palabras: cargamos un <strong>dataset</strong>, separamos <strong>features</strong> y <strong>target</strong>, dividimos en <strong>train y test</strong>, armamos un <strong>pipeline</strong> con <strong>escalado</strong> y un modelo de <strong>clasificación</strong>, revisamos la <strong>estabilidad</strong> con <strong>validación cruzada</strong> y al final medimos con <strong>métricas</strong> sobre datos que el modelo nunca vio.</p>
</section>
<section id="recursos-para-seguir-aprendiendo" class="level2">
<h2 class="anchored" data-anchor-id="recursos-para-seguir-aprendiendo">Recursos para seguir aprendiendo</h2>
<p>Si quieres profundizar, estas son las fuentes oficiales y gratuitas que más uso:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Recurso</th>
<th>Para qué sirve</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><a href="https://www.python.org/">Python</a></td>
<td>El lenguaje base de todo lo que ves en este blog</td>
</tr>
<tr class="even">
<td><a href="https://pandas.pydata.org/docs/user_guide/10min.html">10 minutos con pandas</a></td>
<td>Introducción oficial a <a href="https://pandas.pydata.org/">pandas</a>, la librería para manipular tablas</td>
</tr>
<tr class="odd">
<td><a href="https://numpy.org/">NumPy</a></td>
<td>Cálculo numérico con arreglos; pandas y scikit-learn se apoyan en ella</td>
</tr>
<tr class="even">
<td><a href="https://scikit-learn.org/stable/">scikit-learn</a></td>
<td>Modelos clásicos de Machine Learning, métricas y preprocesamiento</td>
</tr>
<tr class="odd">
<td><a href="https://matplotlib.org/">Matplotlib</a> y <a href="https://seaborn.pydata.org/">seaborn</a></td>
<td>Visualización de datos</td>
</tr>
<tr class="even">
<td><a href="https://jupyter.org/">Jupyter</a></td>
<td>Notebooks para escribir código, gráficos y texto en un mismo lugar</td>
</tr>
<tr class="odd">
<td><a href="https://colab.research.google.com/">Google Colab</a></td>
<td>Notebooks gratis en el navegador, sin instalar nada</td>
</tr>
<tr class="even">
<td><a href="https://www.kaggle.com/learn">Kaggle Learn</a></td>
<td>Cursos cortos y gratuitos con datasets reales para practicar</td>
</tr>
</tbody>
</table>
</section>
<section id="preguntas-frecuentes" class="level2">
<h2 class="anchored" data-anchor-id="preguntas-frecuentes">Preguntas frecuentes</h2>
<p><strong>¿Necesito saber mucha matemática para empezar en Machine Learning?</strong> No para empezar. Con estadística básica y Python puedes avanzar bastante. La matemática se vuelve importante cuando quieres entender por qué los modelos se comportan como lo hacen, y la puedes ir aprendiendo en el camino.</p>
<p><strong>¿Qué lenguaje debo aprender primero para análisis de datos y Machine Learning?</strong> Python. Tiene las librerías más usadas (<a href="https://pandas.pydata.org/">pandas</a>, <a href="https://scikit-learn.org/stable/">scikit-learn</a>, <a href="https://pytorch.org/">PyTorch</a>) y la comunidad más grande. SQL es el segundo idioma que te recomiendo.</p>
<p><strong>¿Cuál es la diferencia entre un analista de datos y un ingeniero de Machine Learning?</strong> El analista responde preguntas con datos y comunica hallazgos. El ingeniero de Machine Learning construye, evalúa y pone en producción modelos que hacen predicciones de forma automática. Comparten muchas bases.</p>
<p><strong>¿Qué es el overfitting en Machine Learning?</strong> Es cuando un modelo memoriza los datos de entrenamiento, incluido el ruido, y por eso funciona muy bien con ellos pero mal con datos nuevos. Lo explico con un gráfico en la sección de overfitting y underfitting.</p>
<p><strong>¿Cuál es la diferencia entre interpretabilidad y explicabilidad?</strong> La interpretabilidad es cuando el propio modelo se puede entender directamente, como los coeficientes de una regresión logística. La explicabilidad es cuando se usa una herramienta externa, como SHAP o LIME, para aproximar por qué un modelo complejo tomó sus decisiones. Lo explico en detalle en la sección de interpretabilidad vs.&nbsp;explicabilidad.</p>
<p><strong>¿Por dónde empiezo?</strong> Por el análisis exploratorio. Aprender a mirar un dataset con criterio es la habilidad que más vas a usar, sin importar el rol.</p>
</section>
<section id="lo-que-viene" class="level2">
<h2 class="anchored" data-anchor-id="lo-que-viene">Lo que viene</h2>
<p>Cada uno de estos conceptos merece su propio post, con datos reales y código paso a paso. El siguiente será sobre <strong>análisis exploratorio de datos</strong>: cómo hacer el primer contacto con un dataset sin perderte.</p>
<p>Si algún término de esta guía te quedó confuso o falta alguno que te gustaría ver, <a href="../../about.html">escríbeme</a>. Este glosario va a ir creciendo.</p>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Volver arriba</a> ]]></description>
  <category>fundamentos</category>
  <category>análisis de datos</category>
  <category>machine learning</category>
  <category>glosario</category>
  <guid>https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/</guid>
  <pubDate>Thu, 08 Oct 2026 00:00:00 GMT</pubDate>
  <media:content url="https://robinsonmirandaco.github.io/posts/conceptos-basicos-analisis-de-datos-machine-learning/portada.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Por qué empiezo un blog de Machine Learning</title>
  <dc:creator>Robinson Miranda</dc:creator>
  <link>https://robinsonmirandaco.github.io/posts/bienvenida/</link>
  <description><![CDATA[ 






<p>Cuando empecé a estudiar Machine Learning en serio me pasó algo que quizá te suene: encontré miles de tutoriales que llegaban hasta <code>model.fit()</code> y ahí se quedaban. Ninguno contaba lo que de verdad ocupa el 80% del trabajo, que es entender los datos antes de modelarlos.</p>
<p>Este blog nace de esa frustración.</p>
<section id="quién-escribe" class="level2">
<h2 class="anchored" data-anchor-id="quién-escribe">Quién escribe</h2>
<p>Soy ingeniero de sistemas y llevo 13 años en tecnología, la mayor parte en calidad de software: análisis de QA, automatización de pruebas y análisis de datos. Acabo de terminar una maestría en Inteligencia Artificial.</p>
<p>Ese recorrido me dejó una obsesión que vas a notar en todo lo que escriba: <strong>no me creo un resultado hasta que puedo reproducirlo y explicarlo</strong>. En pruebas de software aprendí que un sistema no es confiable porque funcione una vez, sino porque puedes demostrar por qué funciona. Con los modelos pasa igual.</p>
<p>Mi tesis fue justamente sobre eso: comparar modelos de deep learning contra métodos clásicos para evaluación de riesgo crediticio, midiendo no solo qué tan bien predicen, sino qué tan estables e interpretables son.</p>
</section>
<section id="para-quién-es-este-blog" class="level2">
<h2 class="anchored" data-anchor-id="para-quién-es-este-blog">Para quién es este blog</h2>
<p>Para quien está empezando en datos y Machine Learning y quiere entender, no solo copiar y pegar. También para quien, como yo, viene de otra área de la tecnología y está haciendo la transición.</p>
<p>No asumo que sepas estadística avanzada. Sí asumo que te animas a correr código.</p>
</section>
<section id="qué-vas-a-encontrar" class="level2">
<h2 class="anchored" data-anchor-id="qué-vas-a-encontrar">Qué vas a encontrar</h2>
<p><strong>Fundamentos con Python.</strong> Análisis exploratorio, limpieza de datos, valores faltantes, outliers, visualización. Lo aburrido que en realidad decide si un proyecto sirve o no.</p>
<p><strong>Modelos, explicados por dentro.</strong> Regresión, clasificación, validación, métricas. Qué hace cada uno, cuándo falla y cómo darte cuenta de que falló.</p>
<p><strong>Proyectos completos.</strong> De los datos crudos hasta una conclusión que se sostenga.</p>
</section>
<section id="cómo-lo-voy-a-hacer" class="level2">
<h2 class="anchored" data-anchor-id="cómo-lo-voy-a-hacer">Cómo lo voy a hacer</h2>
<p>Tres reglas que me impongo:</p>
<ol type="1">
<li><strong>Todo el código se puede ejecutar.</strong> Cada post se escribe como un notebook y se publica con sus resultados reales, no con salidas inventadas.</li>
<li><strong>Datasets públicos.</strong> Si quieres repetir el análisis, puedes.</li>
<li><strong>Explicar el porqué, no solo el cómo.</strong> Un comando sin contexto se olvida en una semana.</li>
</ol>
</section>
<section id="los-primeros-temas" class="level2">
<h2 class="anchored" data-anchor-id="los-primeros-temas">Los primeros temas</h2>
<p>Este es el plan con el que arranco:</p>
<ul>
<li>Análisis exploratorio de datos: primer contacto con un dataset</li>
<li>Valores faltantes: cómo detectarlos y qué hacer con ellos</li>
<li>Outliers: cuándo son error y cuándo son información</li>
<li>Visualización para entender, no para decorar</li>
<li>De los datos limpios al primer modelo</li>
</ul>
<p>Se irá ajustando según lo que resulte más útil.</p>
</section>
<section id="cómo-seguirlo" class="level2">
<h2 class="anchored" data-anchor-id="cómo-seguirlo">Cómo seguirlo</h2>
<p>Puedes suscribirte por <a href="../../blog.xml">RSS</a> o escribirme si quieres que cubra algún tema. Las dudas de quien está aprendiendo son el mejor mapa para saber qué explicar.</p>
<p>Nos leemos en el próximo post.</p>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Volver arriba</a> ]]></description>
  <category>presentación</category>
  <category>machine learning</category>
  <guid>https://robinsonmirandaco.github.io/posts/bienvenida/</guid>
  <pubDate>Sat, 19 Sep 2026 00:00:00 GMT</pubDate>
  <media:content url="https://robinsonmirandaco.github.io/posts/bienvenida/portada.jpg" medium="image" type="image/jpeg"/>
</item>
</channel>
</rss>
