<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"><title>Facundo Roffet</title><link href="https://facuroffet99.github.io/" rel="alternate"></link><link href="https://facuroffet99.github.io/feeds/all.atom.xml" rel="self"></link><id>https://facuroffet99.github.io/</id><updated>2025-12-22T12:40:00-03:00</updated><subtitle>Proyectos de Deep Learning&lt;br&gt;UNS–CONICET</subtitle><entry><title>Losses</title><link href="https://facuroffet99.github.io/notes/losses.html" rel="alternate"></link><published>2025-12-22T12:40:00-03:00</published><updated>2025-12-22T12:40:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-12-22:/notes/losses.html</id><summary type="html">&lt;p&gt;Taxonomía estructurada de funciones de coste (loss functions) en deep learning, organizada por tipo de tarea y mecanismo objetivo. Cubre tareas discriminativas y generativas con énfasis en computer vision y machine learning moderno.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Losses&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;Este post presenta una taxonomía estructurada de loss functions (funciones de coste) utilizadas en Deep Learning, organizándolas por tipo de tarea y mecanismo objetivo. La lista no es exhaustiva, ya que se centra en las losses más ampliamente adoptadas en la investigación moderna de computer vision y machine learning. Se omiten variantes de nicho o altamente especializadas, así como losses específicas para tareas sequence-to-sequence.&lt;/p&gt;
&lt;p&gt;La sección sobre tareas generativas sirve como una visión general amplia de términos en lugar de una lista granular de funciones independientes. Por el contrario, la sección discriminativa proporciona un desglose más detallado de formulaciones específicas.&lt;/p&gt;
&lt;p&gt;El objetivo de esta taxonomía es proporcionar una referencia intuitiva pero matemáticamente rigurosa para seleccionar una loss adecuada en función de los requisitos geométricos y probabilísticos de un problema específico. La categorización y las definiciones presentadas aquí se derivan principalmente de &lt;a href="https://doi.org/10.3390/math13152417"&gt;Li et al. (2025)&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h1&gt;this will be skipped&lt;/h1&gt;
&lt;h1&gt;Tareas discriminativas&lt;/h1&gt;
&lt;p&gt;Optimizan para &lt;span class="math"&gt;\(P(Y|X)\)&lt;/span&gt;. Estas losses se centran en definir fronteras de decisión o ajustar funciones que mapean inputs directamente a targets.&lt;/p&gt;
&lt;h2&gt;D1. Losses de regresión (continuas)&lt;/h2&gt;
&lt;p&gt;Los modelos de regresión apuntan a predecir una variable dependiente continua &lt;span class="math"&gt;\(y\)&lt;/span&gt; basada en variables independientes &lt;span class="math"&gt;\(x\)&lt;/span&gt;. Las losses en esta categoría son funciones de los residuos: la diferencia entre el valor observado &lt;span class="math"&gt;\(y\)&lt;/span&gt; y el valor predicho &lt;span class="math"&gt;\(\hat{y} = f(x)\)&lt;/span&gt;.&lt;/p&gt;
&lt;h3&gt;D1a. Basadas en magnitud (punto a punto)&lt;/h3&gt;
&lt;p&gt;Estas losses miden el error punto a punto entre la predicción y el ground truth. Guían a los modelos para aproximar el valor objetivo minimizando la magnitud de estos errores.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;MAE (Mean Absolute Error)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{MAE} = \frac{1}{N} \sum_{i=1}^{N} |y_i - \hat{y}_i| $$&lt;/div&gt;
&lt;p&gt;
🗒️ Calcula el promedio de las diferencias absolutas entre los valores predichos y los reales.&lt;br&gt;
💡 "No me importa la dirección del error, solo decime en promedio por cuántas unidades le estoy errando. Además, no me voy a volver loco por outliers masivos." &lt;br&gt;
✅ Robusta a outliers (penalización lineal).&lt;br&gt;
✅ Proporciona una unidad física de error que es interpretable.&lt;br&gt;
❌ Los gradientes no son diferenciables en 0, lo que puede complicar la convergencia cerca del óptimo.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;MSE (Mean Squared Error)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{MSE} = \frac{1}{N} \sum_{i=1}^{N} (y_i - \hat{y}_i)^2 $$&lt;/div&gt;
&lt;p&gt;
🗒️ Calcula el promedio de las diferencias al cuadrado. Elevar el error al cuadrado asegura positividad y penaliza los errores grandes desproporcionadamente más que los pequeños.&lt;br&gt;
💡 "Los errores chicos están bien, pero si le errás por mucho te voy a castigar severamente para asegurar que no lo vuelvas a hacer." &lt;br&gt;
✅ Diferenciable en todas partes (descenso de gradiente suave).&lt;br&gt;
✅ Converge más rápido que MAE cuando está cerca del mínimo.&lt;br&gt;
❌ Altamente sensible a outliers, un solo punto de datos malo puede sesgar todo el modelo.&lt;br&gt;
↔️ Variante RMSE: Convierte el error nuevamente a las unidades originales de la variable objetivo tomando la raíz cuadrada, haciéndolo más fácil de interpretar.&lt;br&gt;
↔️ Variante RMSLE: Hace que la loss sea sensible a errores relativos en lugar de absolutos y penaliza la subestimación más que la sobreestimación.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Log-Cosh&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{LogCosh} = \frac{1}{N} \sum_{i=1}^{N} \log(\cosh(\hat{y}_i - y_i)) $$&lt;/div&gt;
&lt;p&gt;
🗒️ Calcula el logaritmo del coseno hiperbólico del error de predicción. Se aproxima a &lt;span class="math"&gt;\(\frac{x^2}{2}\)&lt;/span&gt; para &lt;span class="math"&gt;\(x\)&lt;/span&gt; pequeños y a &lt;span class="math"&gt;\(|x| - \log(2)\)&lt;/span&gt; para &lt;span class="math"&gt;\(x\)&lt;/span&gt; grandes.&lt;br&gt;
💡 "Actuá como MSE cuando el error sea chico para hacer un fine-tuning suave, pero pasate al comportamiento MAE cuando el error sea enorme así los outliers no te distraen." &lt;br&gt;
✅ Combina lo mejor de ambos mundos: robusta a outliers (como MAE) y diferenciable en todas partes (como MSE).&lt;br&gt;
❌ Computacionalmente más costosa que las losses polinómicas simples.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Huber&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$
L_{Huber} = 
\begin{cases}
  \frac{1}{2}(y - \hat{y})^2 &amp;amp; \text{si } |y - \hat{y}| \le \delta \\\\
  \delta \cdot (|y - \hat{y}| - \frac{1}{2}\delta) &amp;amp; \text{en otro caso}
\end{cases}
$$&lt;/div&gt;
&lt;p&gt;
🗒️ Una función a trozos que es cuadrática para errores pequeños (por debajo de un umbral &lt;span class="math"&gt;\(\delta\)&lt;/span&gt;) y lineal para errores grandes. Requiere un hiperparámetro &lt;span class="math"&gt;\(\delta\)&lt;/span&gt; para definir el punto de transición.&lt;br&gt;
💡 "No entres en pánico si un punto de datos está muy lejos, simplemente traelo linealmente. Pero una vez que te acerques, curvá la loss para aterrizar el avión suavemente." &lt;br&gt;
✅ Robusta a outliers manteniendo la diferenciabilidad en 0.&lt;br&gt;
❌ Introduce un hiperparámetro (&lt;span class="math"&gt;\(\delta\)&lt;/span&gt;) que debe ser ajustado.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Quantile&lt;/strong&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$
L_{Quantile} = 
\begin{cases}
  \tau |\hat{y}_i - y_i| &amp;amp; \text{si } |y - \hat{y}| \le \delta \\\\
  (1-\tau)|\hat{y}_i - y_i| &amp;amp; \text{en otro caso}
\end{cases}
$$&lt;/div&gt;
&lt;p&gt; 
🗒️ Una extensión de MAE que aplica diferentes penalizaciones a la sobreestimación y subestimación basada en un cuantil elegido &lt;span class="math"&gt;\(\tau\)&lt;/span&gt; (entre 0 y 1). Se usa para predecir intervalos de predicción en lugar de una media única.&lt;br&gt;
💡 "No quiero solo el resultado promedio, quiero estar 90% seguro de que el valor real está por debajo de mi línea de predicción." &lt;br&gt;
✅ Permite la estimación de incertidumbre y la construcción de intervalos de confianza.&lt;br&gt;
❌ Más difícil de entrenar, la convergencia puede ser más lenta que con MSE/MAE estándar.  &lt;/p&gt;
&lt;h3&gt;D1b. Geometry-aware (bounding boxes)&lt;/h3&gt;
&lt;p&gt;En tareas de detección de objetos, el objetivo de la regresión de bounding boxes es lograr una alineación geométrica entre la caja predicha y el ground truth. A diferencia de las losses basadas en magnitud, las losses geométricas no tratan las coordenadas de forma aislada. En su lugar ven la caja como una entidad geométrica unificada, optimizando la relación espacial (superposición, distancia y forma) entre la predicción y el ground truth.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;IoU (Intersection over Union)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{IoU} = 1 - \frac{|B \cap B^{gt}|}{|B \cup B^{gt}|} $$&lt;/div&gt;
&lt;p&gt;
🗒️ Mide el área de superposición entre la caja predicha &lt;span class="math"&gt;\(B\)&lt;/span&gt; y la caja de ground truth &lt;span class="math"&gt;\(B^{gt}\)&lt;/span&gt; dividida por su área de unión.&lt;br&gt;
💡 "No me importa dónde están los píxeles exactamente, solo asegurate de que los dos cuadrados se superpongan lo máximo posible." &lt;br&gt;
✅ Invariante a la escala del problema (una caja chica y una grande con el mismo % de superposición tienen la misma loss).&lt;br&gt;
❌ Si las cajas no se superponen: IoU es 0, el gradiente es 0, y el modelo deja de aprender completamente.&lt;br&gt;
❌ Si las cajas se superponen completamente: IoU es 1, y el gradiente se vuelve 0 nuevamente.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;GIoU (Generalized IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{GIoU} = 1 - IoU + \frac{|C \setminus (B \cup B^{gt})|}{|C|} $$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(C\)&lt;/span&gt; es la caja convexa más pequeña que cubre tanto a &lt;span class="math"&gt;\(B\)&lt;/span&gt; como a &lt;span class="math"&gt;\(B^{gt}\)&lt;/span&gt;.&lt;br&gt;
🗒️ Agrega un término de penalización basado en el espacio vacío dentro de la caja envolvente más pequeña &lt;span class="math"&gt;\(C\)&lt;/span&gt;. Esto asegura que existan gradientes incluso cuando las cajas no se superponen.&lt;br&gt;
💡 "Si las cajas no se tocan, mové la predicción hacia el target para minimizar el espacio vacío entre ellas." &lt;br&gt;
✅ Resuelve el problema de desvanecimiento de gradiente para cajas que no se superponen.&lt;br&gt;
❌ No resuelve el problema de desvanecimiento de gradiente para cajas completamente superpuestas.&lt;br&gt;
❌ La convergencia es lenta, tiende a expandir la caja predicha para cubrir el target primero antes de encogerse para encajar.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;DIoU (Distance IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{DIoU} = 1 - IoU + \frac{\rho^2(b, b^{gt})}{c^2} $$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(\rho\)&lt;/span&gt; es la distancia Euclidiana, &lt;span class="math"&gt;\(b\)&lt;/span&gt; y &lt;span class="math"&gt;\(b^{gt}\)&lt;/span&gt; son los puntos centrales, y &lt;span class="math"&gt;\(c\)&lt;/span&gt; es la longitud diagonal de la caja envolvente. &lt;br&gt;
🗒️ Agrega una penalización que minimiza la distancia normalizada entre los puntos centrales de las dos cajas.&lt;br&gt;
💡 "No solo superpongas, apuntale al medio. Alineá los centros de las cajas directamente." &lt;br&gt;
✅ Converge mucho más rápido que GIoU porque minimiza la distancia directamente en lugar del área.&lt;br&gt;
✅ Resuelve completamente el problema de desvanecimiento de gradiente.&lt;br&gt;
❌ No considera la relación de aspecto de las cajas.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;CIoU (Complete IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{CIoU} = 1 - IoU + \frac{\rho^2(b, b^{gt})}{c^2} + \alpha v$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(v\)&lt;/span&gt; mide la consistencia de la relación de aspecto y &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; es un parámetro de ponderación.&lt;br&gt;
🗒️ Extiende DIoU agregando un término para asegurar que la relación de aspecto de la predicción coincida con el target.&lt;br&gt;
💡 "Superponé, pegale al centro y asegurate de no estar dibujando un rectángulo alto cuando debería ser uno ancho." &lt;br&gt;
✅ Considera todos los factores geométricos: área de superposición, distancia del punto central y relación de aspecto.&lt;br&gt;
❌ El término de relación de aspecto &lt;span class="math"&gt;\(v\)&lt;/span&gt; es complejo y los gradientes a veces pueden ser inestables dependiendo de la implementación.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;EIoU (Efficient IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{EIoU} = 1 - IoU + \frac{\rho^2(b, b^{gt})}{c^2} + \frac{\rho^2(w, w^{gt})}{C_w^2} + \frac{\rho^2(h, h^{gt})}{C_h^2}$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(w,h\)&lt;/span&gt; son ancho/alto y &lt;span class="math"&gt;\(C_w, C_h\)&lt;/span&gt; son el ancho/alto de la caja envolvente.&lt;br&gt;
🗒️ Mejora CIoU dividiendo el término de relación de aspecto en penalizaciones separadas para las diferencias de ancho y alto.&lt;br&gt;
💡 "La matemática de CIoU es complicada, mejor vamos a medir el error de ancho y el error de alto por separado." &lt;br&gt;
✅ Convergencia más rápida y mejor precisión de localización que CIoU.&lt;br&gt;
✅ Resuelve la ambigüedad en CIoU donde diferentes pares &lt;span class="math"&gt;\(w/h\)&lt;/span&gt; podían producir la misma penalización de relación de aspecto.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;SIoU (Scylla-IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{SIoU} = 1 - IoU + \frac{\Delta + \Omega}{2}$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(\Delta\)&lt;/span&gt; es el costo de distancia y &lt;span class="math"&gt;\(\Omega\)&lt;/span&gt; es el costo de forma.&lt;br&gt;
🗒️ Introduce un costo angular a la regresión. Considera el ángulo vectorial entre el centro de la caja predicha y el ground truth. Prioriza alinear la caja al eje más cercano (X o Y) para minimizar la libertad de movimiento.&lt;br&gt;
💡 "Dejá de dar vueltas en diagonal. Movete estrictamente en horizontal o vertical para alinearte con el target primero, después ajustá el tamaño." &lt;br&gt;
✅ Converge más rápido que CIoU y EIoU reduciendo la oscilación de la caja durante el entrenamiento.&lt;br&gt;
❌ Computacionalmente un poco más pesada debido al cálculo de componentes trigonométricos (seno inverso).  &lt;/p&gt;
&lt;h2&gt;D2. Losses de clasificación (discretas)&lt;/h2&gt;
&lt;p&gt;La clasificación es un subconjunto de tareas de aprendizaje supervisado donde el objetivo es asignar un input &lt;span class="math"&gt;\(x\)&lt;/span&gt; a una de &lt;span class="math"&gt;\(K\)&lt;/span&gt; clases discretas.&lt;/p&gt;
&lt;h3&gt;D2a. Basadas en margen (fronteras de decisión)&lt;/h3&gt;
&lt;p&gt;Las losses de margen introducen un parámetro de umbral para imponer una separación mínima entre el puntaje predicho y la clase correcta. Obligan al modelo no solo a clasificar correctamente, sino a hacerlo con alta confianza manteniendo una 'distancia segura' de la frontera de decisión.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Hinge&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Hinge} = \max(0, 1 - y_i \hat{y}_i)$$&lt;/div&gt;
&lt;p&gt;
🗒️ La loss estándar para Support Vector Machines (SVMs). Solo penaliza al modelo si el puntaje de la clase correcta no es suficientemente más alto que el margen. Si la predicción es correcta y segura (&lt;span class="math"&gt;\(y \hat{y} \ge 1\)&lt;/span&gt;), la loss es cero.&lt;br&gt;
💡 "No quiero solo que tengas razón, quiero que tengas razón por un margen amplio. Si apenas pasás la línea de meta, igual te voy a penalizar." &lt;br&gt;
✅ Los puntos que se clasifican correctamente con alta confianza tienen gradientes 0 y no afectan la actualización del modelo, ahorrando recursos computacionales.&lt;br&gt;
❌ La función no es diferenciable en &lt;span class="math"&gt;\(y\hat{y}=1\)&lt;/span&gt;, requiriendo métodos de optimización de sub-gradiente.&lt;br&gt;
↔️ Variante Squared Hinge: Diferenciable pero sensible a outliers.&lt;br&gt;
↔️ Variante Quadratic Smoothed Hinge: Lineal para errores grandes para mantener robustez, y cuadrática cerca de la frontera del margen para asegurar diferenciabilidad.&lt;br&gt;
↔️ Variante Ramp: Limita la loss para ignorar outliers extremos.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Exponential&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Exp} = e^{-y_i \hat{y}_i}$$&lt;/div&gt;
&lt;p&gt;
🗒️ Utilizada principalmente en algoritmos de boosting como AdaBoost. Aplica una penalización exponencial a márgenes negativos (clasificaciones incorrectas).&lt;br&gt;
💡 "Si te equivocás en un ejemplo difícil, la penalización va a ser masiva. Te tenés que obsesionar con los puntos de datos más difíciles." &lt;br&gt;
✅ Fuerza al modelo a enfocarse intensamente en los ejemplos en los que se está equivocando actualmente.&lt;br&gt;
✅ Diferenciable y convexa.&lt;br&gt;
❌ Debido a que la penalización crece exponencialmente, un solo outlier mal etiquetado puede dominar el gradiente y arruinar el proceso de entrenamiento.  &lt;/p&gt;
&lt;h3&gt;D2b. Probabilísticas (divergencia de distribución)&lt;/h3&gt;
&lt;p&gt;Sea &lt;span class="math"&gt;\(q\)&lt;/span&gt; la distribución de probabilidad verdadera del dataset y &lt;span class="math"&gt;\(p_{\theta}\)&lt;/span&gt; la distribución predicha generada por el modelo. Las losses probabilísticas miden la divergencia (distancia) entre &lt;span class="math"&gt;\(q\)&lt;/span&gt; y &lt;span class="math"&gt;\(p_{\theta}\)&lt;/span&gt;. Al minimizar esta divergencia, la distribución de salida del modelo converge hacia el ground truth.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;CE (Cross-Entropy)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{CE} = -\frac{1}{N} \sum_{i=1}^{N} \sum_{k=1}^{K} y_{i,k} \log(\hat{y}_{i,k})$$&lt;/div&gt;
&lt;p&gt;
🗒️ Mide la diferencia de información entre la distribución predicha y la distribución verdadera. Cuando los targets están codificados en one-hot, minimizar CE es matemáticamente equivalente a maximizar la verosimilitud (likelihood) de la clase correcta.&lt;br&gt;
💡 "Si la imagen es un gato, quiero que la probabilidad de 'gato' sea 1.0. Cada pedacito de masa de probabilidad asignada a 'perro' o 'pájaro' aumenta la penalización." &lt;br&gt;
✅ La loss por defecto para clasificación, diferenciable y rigurosamente basada en Teoría de la Información.&lt;br&gt;
❌ Dominada por clases mayoritarias si los datos están desbalanceados.&lt;br&gt;
❌ Dominada por ejemplos fáciles (fondo) en tareas de detección densa.&lt;br&gt;
↔️ Variante Weighted CE: Multiplica la loss de la clase &lt;span class="math"&gt;\(k\)&lt;/span&gt; por un peso &lt;span class="math"&gt;\(\alpha_k\)&lt;/span&gt; (usualmente inverso a la frecuencia de clase o al número efectivo de muestras).&lt;br&gt;
↔️ Variante Label Smoothing: Cambia el target &lt;span class="math"&gt;\(y=1\)&lt;/span&gt; a &lt;span class="math"&gt;\(y=1-\epsilon\)&lt;/span&gt; y &lt;span class="math"&gt;\(y=0\)&lt;/span&gt; a &lt;span class="math"&gt;\(y=\frac{\epsilon}{K-1}\)&lt;/span&gt; para prevenir el overfitting.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Focal&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Focal} = -\frac{1}{N} \sum_{i=1}^{N} \alpha (1 - \hat{p}_i)^\gamma \log(\hat{p}_i)$$&lt;/div&gt;
&lt;p&gt;
🗒️ Agrega un factor modulador &lt;span class="math"&gt;\((1 - \hat{p}_i)^\gamma\)&lt;/span&gt; a la Cross-Entropy estándar. Si una muestra ya está bien clasificada (ej., &lt;span class="math"&gt;\(\hat{p}_i = 0.9\)&lt;/span&gt;), el factor se acerca a 0, silenciando efectivamente la loss para ese ejemplo.&lt;br&gt;
💡 "No me importa el cielo de fondo que ya identificaste correctamente 1.000 veces. Concentrate en ese único píxel difícil que parece un peatón." &lt;br&gt;
✅ Resuelve el problema de desbalance de clases sin sobremuestreo manual.&lt;br&gt;
✅ El estándar para detección de objetos densa.&lt;br&gt;
❌ Requiere ajustar dos hiperparámetros (&lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; y &lt;span class="math"&gt;\(\gamma\)&lt;/span&gt;) que pueden ser sensibles al dataset.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;GHM (Gradient Harmonized Mechanism)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{GHM} = \sum_{i=1}^{N} \frac{L_{CE}}{GD(g_i)}$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(g_i\)&lt;/span&gt; es la norma del gradiente y &lt;span class="math"&gt;\(GD\)&lt;/span&gt; es la densidad de gradiente (una medida de cuántas muestras tienen ese mismo gradiente).&lt;br&gt;
🗒️ Una alternativa avanzada a Focal loss. Observa que los ejemplos fáciles y los outliers tienen comportamientos de gradiente distintos. Armoniza el entrenamiento normalizando la loss basada en la densidad de gradientes. Si un millón de ejemplos producen el mismo gradiente pequeño (fondo fácil), su contribución se divide por un factor de densidad grande.&lt;br&gt;
💡 "Si todos los demás están gritando lo mismo, voy a bajarle el volumen a ese grupo. Solo quiero escuchar los errores únicos/raros." &lt;br&gt;
✅ No requiere ajuste manual de &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; o &lt;span class="math"&gt;\(\gamma\)&lt;/span&gt; como Focal loss, se adapta a la dinámica de los datos de entrenamiento.&lt;br&gt;
❌ El costo computacional aumenta: requiere calcular un histograma de gradientes a través del batch/dataset durante el entrenamiento.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Poly&lt;/strong&gt;  &lt;/p&gt;
&lt;div class="math"&gt;$$
L_{Poly} = -\sum_{j=1}^{\infty} \alpha_j (1 - \hat{p}_t)^j 
$$&lt;/div&gt;
&lt;p&gt;🗒️ Trata a la Cross-Entropy como una expansión en serie de Taylor y la generaliza, permitiendo el ajuste de los coeficientes polinómicos principales &lt;span class="math"&gt;\(\alpha_j\)&lt;/span&gt; para cambiar estructuralmente cómo se comporta la loss (en lugar de tenerlos fijos en &lt;span class="math"&gt;\(1/j\)&lt;/span&gt;). En la práctica, usualmente solo se modifica el coeficiente principal (&lt;span class="math"&gt;\(\epsilon_1\)&lt;/span&gt;): &lt;span class="math"&gt;\(L_{Poly-1} = L_{CE} + \epsilon_1 (1 - \hat{p}_t)\)&lt;/span&gt;.&lt;br&gt;
💡 "Cross-Entropy es una curva fija, pero podemos cambiarle la forma si lo necesitamos." &lt;br&gt;
✅ Función generalizada que abarca Cross-Entropy y Focal Loss como casos especiales.&lt;br&gt;
✅ Poly-1 suele superar a Focal/CE ajustando un solo parámetro, con un costo computacional adicional despreciable.&lt;br&gt;
❌ Introduce un hiperparámetro no estándar que debe encontrarse mediante grid search, ya que no hay un valor por defecto universal.  &lt;/p&gt;
&lt;h3&gt;D2c. Overlap-based (segmentación)&lt;/h3&gt;
&lt;p&gt;En segmentación semántica, la clasificación ocurre a nivel de píxel. Sin embargo, las losses pixel-wise a menudo tienen problemas cuando el objeto objetivo ocupa solo una pequeña fracción de la imagen. Las losses basadas en superposición abordan esto optimizando directamente la intersección entre el mapa de segmentación predicho y el ground truth, priorizando la alineación global de la forma sobre la precisión individual de los píxeles.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tversky&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Tversky} = 1 - \frac{\sum \hat{y} y}{\sum \hat{y} y + \alpha \sum (1-y)\hat{y} + \beta \sum y(1-\hat{y})}$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(y\)&lt;/span&gt; es el target, &lt;span class="math"&gt;\(\hat{y}\)&lt;/span&gt; es la predicción, &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; controla la penalización para falsos positivos, y &lt;span class="math"&gt;\(\beta\)&lt;/span&gt; controla la penalización para falsos negativos.&lt;br&gt;
🗒️ Una generalización del coeficiente Dice (cuando &lt;span class="math"&gt;\(\alpha = \beta = 0.5\)&lt;/span&gt;). Permite cambiar el balance entre precisión (evitar falsos positivos) y recall (evitar falsos negativos).&lt;br&gt;
💡 "Si encontrar el tumor es crítico y no podemos permitirnos perderlo, poné &lt;span class="math"&gt;\(\beta\)&lt;/span&gt; más alto que &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; para penalizar a los píxeles perdidos más que los que sobran." &lt;br&gt;
✅ Mucho mejor que Cross-Entropy para manejar desbalance en objetos pequeños.&lt;br&gt;
✅ Los parámetros &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; y &lt;span class="math"&gt;\(\beta\)&lt;/span&gt; dan flexibilidad para ajustar el trade-off en base a las necesidades clínicas o de negocio.&lt;br&gt;
❌ Puede ser inestable durante las etapas tempranas del entrenamiento comparada con CE pixel-wise.&lt;br&gt;
↔️ Variante Focal Tversky: Aplica el mecanismo de Focal loss al índice Tversky.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sensitivity-Specificity&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{SS} = w \cdot \frac{\sum (y-\hat{y})^2 y}{\sum y} + (1-w) \cdot \frac{\sum (y-\hat{y})^2 (1-y)}{\sum (1-y)}$$&lt;/div&gt;
&lt;p&gt;
🗒️ Optimiza explícitamente la suma ponderada de los errores cuadráticos para la clase positiva (sensibilidad) y la clase negativa (especificidad). Asegura que el modelo no logre alta precisión simplemente ignorando el fondo o el primer plano.&lt;br&gt;
💡 "Necesito que seas bueno encontrando el objeto, pero igual de bueno NO encontrando el objeto donde no existe. Balanceá tu entusiasmo." &lt;br&gt;
✅ Aborda tanto la sobre-segmentación (incluir demasiado fondo) como la sub-segmentación (perder partes del objeto).&lt;br&gt;
✅ Apropiada para contextos médicos donde la especificidad es tan vital como la sensibilidad.&lt;br&gt;
❌ Altamente sensible al parámetro de peso &lt;span class="math"&gt;\(w\)&lt;/span&gt;. Si se configura incorrectamente, el modelo puede colapsar prediciendo solo el fondo o solo el primer plano.  &lt;/p&gt;
&lt;h2&gt;D3. Losses métricas (espacio de embeddings)&lt;/h2&gt;
&lt;p&gt;El objetivo del aprendizaje métrico es aprender las distancias relativas entre inputs en lugar de predecir una etiqueta o valor específico. Las losses métricas operan sobre pares (o tripletes) de instancias de datos, extrayendo un embedding para cada una. Una métrica de distancia mide la similitud entre estas representaciones. El modelo se entrena para minimizar la distancia entre representaciones de inputs similares y maximizar la distancia entre los disímiles, estructurando el espacio de embeddings de manera significativa.&lt;/p&gt;
&lt;h3&gt;D3a. Distancia Euclídea&lt;/h3&gt;
&lt;p&gt;Estas losses usan directamente la distancia geométrica en el espacio de embeddings como el objetivo de optimización.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Contrastive Loss&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Contrastive} = \frac{1}{2} \sum_{i=1}^{N} [Y_iD_i^2 + (1-Y_i) \max(0, m - D_i)^2]$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(D = ||f(x_1) - f(x_2)||_2\)&lt;/span&gt; es la distancia Euclídea entre el par de muestras, &lt;span class="math"&gt;\(Y=1\)&lt;/span&gt; implica misma clase, &lt;span class="math"&gt;\(Y=0\)&lt;/span&gt; implica clase diferente, y &lt;span class="math"&gt;\(m\)&lt;/span&gt; es el margen.&lt;br&gt;
🗒️ Toma pares de muestras. Si pertenecen a la misma clase, minimiza su distancia. Si pertenecen a clases diferentes, las empuja hasta que estén al menos a un margen &lt;span class="math"&gt;\(m\)&lt;/span&gt; de distancia.&lt;br&gt;
💡 "Si son gemelos, abrácense. Si son desconocidos, aléjense hasta que tengan al menos 1 metro de espacio personal entre ustedes." &lt;br&gt;
✅ Es el enfoque fundacional simple para el aprendizaje métrico.&lt;br&gt;
❌ Difícil ajustar el margen. Si &lt;span class="math"&gt;\(m\)&lt;/span&gt; es muy chico, los clusters se superponen; si es muy grande, el entrenamiento se vuelve inestable.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Triplet&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Triplet} = \sum_{i=1}^{N} \max(0, D(a_i, p_i)^2 - D(a_i, n_i)^2 + m)$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(a\)&lt;/span&gt; es ancla, &lt;span class="math"&gt;\(p\)&lt;/span&gt; es positivo (misma clase), &lt;span class="math"&gt;\(n\)&lt;/span&gt; es negativo (clase diferente), y &lt;span class="math"&gt;\(m\)&lt;/span&gt; es margen.&lt;br&gt;
🗒️ Toma tres muestras a la vez: un ancla, un positivo y un negativo. Asegura que el ancla esté más cerca del positivo que del negativo por al menos un margen &lt;span class="math"&gt;\(m\)&lt;/span&gt;.&lt;br&gt;
💡 "No me importa exactamente dónde está el ancla, siempre y cuando su amigo (positivo) esté más cerca de ella que su enemigo (negativo)." &lt;br&gt;
✅ Más flexible que Contrastive loss porque relaja la restricción sobre distancias absolutas, solo importa el ranking relativo.&lt;br&gt;
❌ Requiere encontrar negativos que estén actualmente más cerca que los positivos. Si se eligen negativos al azar, la loss suele ser 0 y el modelo no aprende nada.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;InfoNCE (Information Noise-Contrastive Estimation)&lt;/strong&gt;&lt;br&gt;
🗒️ Trata la tarea como un problema de clasificación: "Entre este batch de &lt;span class="math"&gt;\(K\)&lt;/span&gt; negativos y 1 positivo, identificá el positivo". Maximiza la información mutua entre la query y la key positiva.&lt;br&gt;
💡 "Acá tenés una foto de un perro y 1.000 fotos de otras cosas. ¿Podés elegir el perro correcto de esta rueda de reconocimiento?" &lt;br&gt;
✅ Aprende de un positivo y muchos negativos simultáneamente, proporcionando una señal de gradiente mucho más rica que Triplet.&lt;br&gt;
✅ Es el backbone estándar para el aprendizaje de representación auto-supervisado moderno.&lt;br&gt;
❌ A menudo requiere un batch size muy grande para tener suficientes negativos difíciles y funcionar eficazmente.  &lt;/p&gt;
&lt;h3&gt;D3b. Margen angular&lt;/h3&gt;
&lt;p&gt;Las losses basadas en márgenes angulares o coseno no optimizan directamente la posición absoluta y la distancia en el espacio de features. En cambio, se centran en las fronteras angulares entre clases proyectando features en una hiperesfera y optimizando la similitud coseno entre vectores de features y centros de clases.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A-Softmax (Angular Softmax / SphereFace)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Sphere} = -\log \frac{e^{||x_i|| \psi(\theta_{y_i})}}{e^{||x_i|| \psi(\theta_{y_i})} + \sum_{j \neq y_i} e^{||x_i|| \cos(\theta_j)}}$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(\psi(\theta)\)&lt;/span&gt; es una función monotónica que reemplaza &lt;span class="math"&gt;\(\cos(\theta)\)&lt;/span&gt; con &lt;span class="math"&gt;\(\cos(m\theta)\)&lt;/span&gt;.&lt;br&gt;
🗒️ La primera loss angular. Introduce un margen angular multiplicativo &lt;span class="math"&gt;\(m\)&lt;/span&gt;, y fuerza al ángulo de la clase correcta a ser &lt;span class="math"&gt;\(m\)&lt;/span&gt; veces más pequeño que el ángulo de cualquier clase incorrecta.&lt;br&gt;
💡 "Si el ángulo al centro de tu clase es 10 grados, voy a hacer de cuenta que en realidad es 40 grados (&lt;span class="math"&gt;\(m=4\)&lt;/span&gt;). Tenés que trabajar 4 veces más duro para demostrar que pertenecés ahí." &lt;br&gt;
✅ Pionera en el concepto de márgenes angulares, demostrando que las restricciones geométricas en la hiperesfera mejoran significativamente la discriminación de features.&lt;br&gt;
❌ La optimización es difícil y requiere un annealing complejo del hiperparámetro &lt;span class="math"&gt;\(\lambda\)&lt;/span&gt; para converger.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;AM-Softmax (Additive Margin Softmax / CosFace)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Cos} = -\log (\frac{e^{s(\cos(\theta_{y_i}) - m)}}{e^{s(\cos(\theta_{y_i}) - m)} + \sum_{j \neq y_i} e^{s \cos(\theta_j)}})$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(s\)&lt;/span&gt; es un factor de escala y &lt;span class="math"&gt;\(m\)&lt;/span&gt; es un margen de coseno aditivo.&lt;br&gt;
🗒️ Simplifica SphereFace moviendo el margen &lt;span class="math"&gt;\(m\)&lt;/span&gt; fuera de la función coseno. Resta un margen &lt;span class="math"&gt;\(m\)&lt;/span&gt; directamente del valor de similitud coseno.&lt;br&gt;
💡 "La Softmax estándar es muy permisiva. Le voy a restar 0.3 a tu puntaje de similitud. Efectivamente necesitás un puntaje de 1.3 para obtener un 1.0 perfecto. ¡Esforzate más!" &lt;br&gt;
✅ Mucho más fácil de implementar y entrenar que SphereFace.&lt;br&gt;
✅ Es más interpretable ya que optimiza directamente el gap de similitud coseno.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Additive Angular Margin (ArcFace)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Arc} = -\log (\frac{e^{s \cos(\theta_{y_i} + m)}}{e^{s \cos(\theta_{y_i} + m)} + \sum_{j \neq y_i} e^{s \cos(\theta_j)}})$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(m\)&lt;/span&gt; es un margen angular aditivo sumado dentro del coseno.&lt;br&gt;
🗒️ Agrega el margen &lt;span class="math"&gt;\(m\)&lt;/span&gt; dentro del término coseno, lo que corresponde a una penalización de distancia geodésica directa en la hiperesfera.&lt;br&gt;
💡 "Imaginate que las clases son países en un globo terráqueo. ArcFace dibuja fronteras estrictas con una zona buffer entre cada país directamente sobre la superficie de la esfera." &lt;br&gt;
✅ El margen tiene una correspondencia constante con la longitud de arco en la hiperesfera.&lt;br&gt;
✅ Es state-of-the-art para reconocimiento facial.&lt;br&gt;
❌ Requiere un ajuste cuidadoso de la escala &lt;span class="math"&gt;\(s\)&lt;/span&gt; y el margen &lt;span class="math"&gt;\(m\)&lt;/span&gt; dependiendo del ruido del dataset.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Quality Adaptive Margin Softmax (AdaFace)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Ada} = -\log (\frac{e^{s \cos(\theta_{y_i} + g_{angle})}}{e^{s \cos(\theta_{y_i} + g_{angle})} + \sum_{j \neq y_i} e^{s \cos(\theta_j)}})$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(g_{angle}\)&lt;/span&gt; es una función de margen que se adapta basada en la calidad de la imagen (norma del feature &lt;span class="math"&gt;\(||\hat{z}_i||\)&lt;/span&gt;).&lt;br&gt;
🗒️ Adapta el margen basado en la calidad de la imagen de entrada. Aplica un margen estricto a imágenes de alta calidad y un margen relajado a imágenes de baja calidad para evitar que el modelo haga overfitting al ruido.&lt;br&gt;
💡 "Si la foto es HD, espero perfección. Si la foto es un cuadro borroso de una cámara de seguridad, voy a ser más suave con vos para que no te confundas tratando de aprender ruido." &lt;br&gt;
✅ Estado del arte para reconocimiento facial no restringido (ej., vigilancia, baja resolución).&lt;br&gt;
✅ Evita que el modelo se trabe tratando de optimizar muestras irreconociblemente.&lt;br&gt;
❌ Introduce complejidad en la implementación y depende de la asunción de que la norma del feature correlaciona con la calidad de la imagen (lo cual suele ser cierto, pero no siempre).  &lt;/p&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h1&gt;Tareas generativas&lt;/h1&gt;
&lt;p&gt;Optimizan para &lt;span class="math"&gt;\(P(X)\)&lt;/span&gt; o &lt;span class="math"&gt;\(P(X,Y)\)&lt;/span&gt;. Las losses para estas tareas se enfocan en aprender la distribución de datos subyacente para generar nuevas muestras o reconstruir inputs. Estas funciones objetivo suelen ser compuestas, mezclando múltiples términos (reconstrucción, coincidencia de distribución, calidad perceptual) para lograr resultados realistas.&lt;/p&gt;
&lt;h2&gt;G1. Términos de reconstrucción (element-wise)&lt;/h2&gt;
&lt;p&gt;Estos términos aseguran fidelidad midiendo la diferencia directa entre el input original &lt;span class="math"&gt;\(x\)&lt;/span&gt; y el output reconstruido/generado &lt;span class="math"&gt;\(\hat{x}\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;MSE (Mean Squared Error)&lt;/strong&gt;&lt;br&gt;
🗒️ Es la misma función usada para tareas discriminativas. Para tareas generativas, esto actúa como el término de "fidelidad".&lt;br&gt;
💡 "La imagen generada se tiene que ver exactamente como el input, píxel por píxel." &lt;br&gt;
✅ Simple de implementar y garantiza teóricamente el PSNR (Peak Signal-to-Noise Ratio) más alto.&lt;br&gt;
❌ En contextos generativos, MSE puro tiende a producir imágenes borrosas porque promedia los detalles de alta frecuencia.  &lt;/p&gt;
&lt;h2&gt;G2. Términos de coincidencia de distribución (divergencias)&lt;/h2&gt;
&lt;p&gt;Estos términos minimizan la discrepancia estadística entre la distribución aprendida &lt;span class="math"&gt;\(P_g\)&lt;/span&gt; y la distribución de datos real &lt;span class="math"&gt;\(P_{data}\)&lt;/span&gt;. Son centrales en GANs y Variational Autoencoders (VAEs).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Minimax (GAN loss)&lt;/strong&gt;&lt;br&gt;
🗒️ Un juego de suma cero entre dos redes: un generador (&lt;span class="math"&gt;\(G\)&lt;/span&gt;) intenta engañar al discriminador, y un discriminador (&lt;span class="math"&gt;\(D\)&lt;/span&gt;) intenta distinguir real de falso.&lt;br&gt;
💡 "Generador: Apuesto a que te puedo engañar. Discriminador: No, no podés, voy a detectar el falso." &lt;br&gt;
✅ Produce detalles muy nítidos y realistas comparado con MSE.&lt;br&gt;
❌ Muy difícil de entrenar.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Wasserstein Distance (WGAN loss)&lt;/strong&gt;&lt;br&gt;
🗒️ Calcula el "trabajo" mínimo (masa × distancia) requerido para transformar una distribución en otra. A diferencia de la loss GAN estándar, el discriminador (ahora llamado crítico) emite un puntaje crudo, no una probabilidad.&lt;br&gt;
💡 "En lugar de preguntar '¿Verdadero o Falso?', mejor preguntá '¿Qué tan real es esto?' para dejarle saber al generador exactamente cuán lejos está del target, incluso si actualmente está fallando por completo." &lt;br&gt;
✅ Proporciona gradientes significativos incluso cuando las distribuciones real y falsa no se superponen en absoluto, resolviendo el problema de desvanecimiento de gradiente de las GANs estándar.&lt;br&gt;
✅ El valor de la loss correlaciona linealmente con la calidad visual de las imágenes generadas, lo cual no es cierto para la loss GAN estándar.&lt;br&gt;
❌ Requiere imponer continuidad 1-Lipschitz (el gradiente no puede cambiar muy rápido), lo cual es difícil de implementar.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;KL (Kullback-Leibler Divergence)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{KL} = \sum P(x) \log (\frac{P(x)}{Q(x)}) $$&lt;/div&gt;
&lt;p&gt;
🗒️ Mide cuánta información se pierde cuando la distribución &lt;span class="math"&gt;\(Q\)&lt;/span&gt; se usa para aproximar &lt;span class="math"&gt;\(P\)&lt;/span&gt;. En VAEs, fuerza al espacio latente aprendido a seguir una distribución Gaussiana estándar.&lt;br&gt;
💡 "Mantené tu espacio latente organizado como una campana de Gauss estándar así podemos muestrear de él fácilmente después." &lt;br&gt;
✅ Fuerza a las variables latentes aprendidas a seguir una distribución tratable (usualmente Gaussiana Unitaria), asegurando que el espacio latente sea suave y continuo.&lt;br&gt;
❌ La restricción Gaussiana estricta a menudo resulta en salidas sobre-regularizadas y borrosas.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sinkhorn Divergence&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Sinkhorn} = \min_{\pi} \sum_{i,j} C_{i,j} \pi_{i,j} + \epsilon H(\pi)$$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(C\)&lt;/span&gt; es la matriz de costo, &lt;span class="math"&gt;\(\pi\)&lt;/span&gt; es el plan de transporte, y &lt;span class="math"&gt;\(H\)&lt;/span&gt; es la entropía de regularización.&lt;br&gt;
🗒️ Agrega un término de regularización entrópica al problema de transporte óptimo. Esto permite que la distancia Wasserstein sea calculada mucho más rápido usando el algoritmo Sinkhorn-Knopp.&lt;br&gt;
💡 "Calcular el plan perfecto de movimiento de tierra es difícil. Si permitimos un poco de aleatoriedad en a dónde va la tierra, podemos resolver la matemática 100 veces más rápido." &lt;br&gt;
✅ Diferenciable y computacionalmente lo suficientemente rápida para usarse como loss.&lt;br&gt;
❌ Si &lt;span class="math"&gt;\(\epsilon\)&lt;/span&gt; es muy grande, la métrica se vuelve demasiado borrosa y pierde la precisión geométrica de la distancia Wasserstein verdadera.  &lt;/p&gt;
&lt;h2&gt;G3. Términos de difusión (eliminación de ruido)&lt;/h2&gt;
&lt;p&gt;Usados en Diffusion Probabilistic Models (DDPMs). El objetivo es revertir un proceso de ruido gradual.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Simple Diffusion&lt;/strong&gt; &lt;br&gt;
🗒️ El modelo predice el ruido &lt;span class="math"&gt;\(\epsilon\)&lt;/span&gt; que fue agregado a la imagen &lt;span class="math"&gt;\(x_0\)&lt;/span&gt; en el paso de tiempo &lt;span class="math"&gt;\(t\)&lt;/span&gt;.&lt;br&gt;
💡 "Te voy a mostrar una pantalla de TV con ruido. Decime exactamente qué píxeles son ruido para que pueda restarlos y revelar la imagen de abajo." &lt;br&gt;
✅ El entrenamiento es esencialmente un conjunto masivo de tareas de regresión (MSE sobre ruido), lo cual es mucho más estable comparado con GANs.&lt;br&gt;
❌ La inferencia es lenta, ya que generar una sola imagen requiere correr la red iterativamente (ej., 50 a 1000 veces) para eliminar el ruido paso a paso.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Denoising Score Matching&lt;/strong&gt;&lt;br&gt;
🗒️ Optimiza el modelo para estimar la función de score (el gradiente de la log-densidad de los datos). Al moverse a lo largo del gradiente, se mueve desde un punto de datos ruidosos hacia un punto de datos limpios.&lt;br&gt;
💡 "Te tiran en un bosque con niebla. No sabés dónde está la cima de la montaña, pero si mirás tus pies y pisás donde el suelo va hacia arriba, eventualmente vas a llegar." &lt;br&gt;
✅ Evita el problema intratable de calcular la constante de normalización de la distribución de probabilidad.&lt;br&gt;
❌ Técnicamente compleja de derivar e implementar comparada con el objetivo simplificado usado en Simple Diffusion.  &lt;/p&gt;
&lt;h2&gt;G4. Términos de guía auxiliar (basados en features)&lt;/h2&gt;
&lt;p&gt;En lugar de comparar píxeles crudos, estas losses comparan representaciones de alto nivel extraídas por una red pre-entrenada.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Perceptual&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{Perc} = || \phi(x) - \phi(\hat{x}) ||_2^2 $$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(\phi\)&lt;/span&gt; es un extractor de features pre-entrenado.&lt;br&gt;
🗒️ Compara los mapas de activación internos de una red pre-entrenada para las imágenes reales y generadas.&lt;br&gt;
💡 "No me importa si el píxel exacto coincide. ¿La imagen parece un perro? ¿Los bordes y texturas coinciden con la percepción humana?" &lt;br&gt;
✅ Correlaciona mucho mejor con el juicio visual humano que MSE, y proporciona texturas excelentes para transferencia de estilo y super-resolución.&lt;br&gt;
❌ Depende de redes pre-entrenadas, por lo que puede fallar o producir artefactos si el dominio objetivo es vastamente diferente.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Style&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{Style} = || G(\phi(x)) - G(\phi(\hat{x})) ||_F^2 $$&lt;/div&gt;
&lt;p&gt;
Donde &lt;span class="math"&gt;\(G\)&lt;/span&gt; calcula la Matriz de Gram—correlaciones entre features.&lt;br&gt;
🗒️ Mide la correlación entre diferentes canales de features. Captura el "estilo" (textura, pinceladas, patrones de color) mientras descarta la estructura espacial.&lt;br&gt;
💡 "Capturá la onda de Van Gogh pero no te preocupes por dónde están ubicados los árboles." &lt;br&gt;
✅ Desacopla explícitamente la textura de la estructura, permitiendo la síntesis de patrones artísticos complejos sin necesitar datos de entrenamiento pareados.&lt;br&gt;
❌ No impone coherencia espacial, por lo que parches de textura pueden aparecer en ubicaciones semánticamente incorrectas (ej., pinceladas apareciendo en el cielo en lugar de los árboles).&lt;/p&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (true) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=TeX-AMS-MML_HTMLorMML';

    var configscript = document.createElement('script');
    configscript.type = 'text/x-mathjax-config';
    configscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'none'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        availableFonts: ['STIX', 'TeX']," +
        "        preferredFont: 'STIX'," +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";

    (document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="Deep Learning"></category></entry><entry><title>Loss functions</title><link href="https://facuroffet99.github.io/en/notes/losses.html" rel="alternate"></link><published>2025-12-22T12:40:00-03:00</published><updated>2025-12-22T12:40:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-12-22:/en/notes/losses.html</id><summary type="html">&lt;p&gt;A structured taxonomy of loss functions in deep learning, organized by task type and objective mechanism. Covers discriminative and generative tasks with a focus on modern computer vision and machine learning.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Loss functions&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;This post presents a structured taxonomy of loss functions used in deep learning, organizing them by task type and objective mechanism. The list is not exhaustive, as it focuses on the most widely adopted losses in modern computer vision and machine learning research. Niche or highly specialized variants are omitted, as well as losses specific to sequence-to-sequence tasks.&lt;/p&gt;
&lt;p&gt;The section on generative tasks serves as a broad overview of terms rather than a granular list of standalone functions. Conversely, the discriminative section provides a more detailed breakdown of specific formulations.&lt;/p&gt;
&lt;p&gt;The goal of this taxonomy is to provide an intuitive yet mathematically rigorous reference for selecting the appropriate loss function based on the geometric and probabilistic requirements of a specific problem. The categorization and definitions presented here are primarily derived from &lt;a href="https://doi.org/10.3390/math13152417"&gt;Li et al. (2025)&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h1&gt;this will be skipped&lt;/h1&gt;
&lt;h1&gt;Discriminative tasks&lt;/h1&gt;
&lt;p&gt;Optimize for &lt;span class="math"&gt;\(P(Y|X)\)&lt;/span&gt;. These losses focus on defining decision boundaries or fitting functions that map inputs directly to targets.&lt;/p&gt;
&lt;h2&gt;D1. Regression losses (continuous)&lt;/h2&gt;
&lt;p&gt;Regression models aim to predict a continuous dependent variable &lt;span class="math"&gt;\(y\)&lt;/span&gt; based on independent variables &lt;span class="math"&gt;\(x\)&lt;/span&gt;. Losses in this category are functions of the residuals—the difference between the observed value &lt;span class="math"&gt;\(y\)&lt;/span&gt; and the predicted value &lt;span class="math"&gt;\(\hat{y} = f(x)\)&lt;/span&gt;. &lt;/p&gt;
&lt;h3&gt;D1a. Magnitude-based (point-wise)&lt;/h3&gt;
&lt;p&gt;These losses measure the point-wise error between the prediction and the ground truth. They guide models to approximate the target value by minimizing the magnitude of these errors.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;MAE (Mean Absolute Error)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{MAE} = \frac{1}{N} \sum_{i=1}^{N} |y_i - \hat{y}_i| $$&lt;/div&gt;
&lt;p&gt;
🗒️ Calculates the average of the absolute differences between the predicted and actual values.&lt;br&gt;
💡 "I don't care about the direction of the error, just tell me on average how many units I am off by. Also, I won't freak out over massive outliers." &lt;br&gt;
✅ Robust to outliers (linear penalty).&lt;br&gt;
✅ Provides a physical unit of error that is interpretable.&lt;br&gt;
❌ Gradients are non-differentiable at 0, which can complicate convergence near the optimum.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;MSE (Mean Squared Error)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{MSE} = \frac{1}{N} \sum_{i=1}^{N} (y_i - \hat{y}_i)^2 $$&lt;/div&gt;
&lt;p&gt;
🗒️ Calculates the average of the squared differences. Squaring the error ensures positivity and penalizes larger errors disproportionately more than small ones.&lt;br&gt;
💡 "Small mistakes are okay, but if you make a huge mistake, I am going to punish you severely to make sure you never do it again." &lt;br&gt;
✅ Differentiable everywhere (smooth gradient descent).&lt;br&gt;
✅ Converges faster than MAE when close to the minimum.&lt;br&gt;
❌ Highly sensitive to outliers, one bad data point can skew the entire model.&lt;br&gt;
↔️ Variant RMSE: Converts the error back into the original units of the target variable by taking the square root, making it easier to interpret.&lt;br&gt;
↔️ Variant RMSLE: Makes the loss sensitive to relative errors rather than absolute ones and penalizes underestimation more than overestimation.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Log-Cosh&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{LogCosh} = \frac{1}{N} \sum_{i=1}^{N} \log(\cosh(\hat{y}_i - y_i)) $$&lt;/div&gt;
&lt;p&gt;
🗒️ Computes the logarithm of the hyperbolic cosine of the prediction error. It approximates &lt;span class="math"&gt;\(\frac{x^2}{2}\)&lt;/span&gt; for small &lt;span class="math"&gt;\(x\)&lt;/span&gt; and &lt;span class="math"&gt;\(|x| - \log(2)\)&lt;/span&gt; for large &lt;span class="math"&gt;\(x\)&lt;/span&gt;.&lt;br&gt;
💡 "Act like MSE when the error is small to fine-tune gently, but switch to MAE behavior when the error is huge so outliers don't distract you." &lt;br&gt;
✅ Combines the best of both worlds: robust to outliers (like MAE) and differentiable everywhere (like MSE).&lt;br&gt;
❌ Computationally more expensive than simple polynomial losses.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Huber&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$
L_{Huber} = 
\begin{cases}
  \frac{1}{2}(y - \hat{y})^2 &amp;amp; \text{if } |y - \hat{y}| \le \delta \\\\
  \delta \cdot (|y - \hat{y}| - \frac{1}{2}\delta) &amp;amp; \text{otherwise}
\end{cases}
$$&lt;/div&gt;
&lt;p&gt;
🗒️ A piecewise function that is quadratic for small errors (below a threshold &lt;span class="math"&gt;\(\delta\)&lt;/span&gt;) and linear for large errors. It requires a hyperparameter &lt;span class="math"&gt;\(\delta\)&lt;/span&gt; to define the transition point.&lt;br&gt;
💡 "Don't panic if a data point is way off, just pull it in linearly. But once you get close, curve the loss to land the plane smoothly." &lt;br&gt;
✅ Robust to outliers while maintaining differentiability at 0.&lt;br&gt;
❌ Introduces a hyperparameter (&lt;span class="math"&gt;\(\delta\)&lt;/span&gt;) that must be tuned.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Quantile&lt;/strong&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$
L_{Quantile} = 
\begin{cases}
  \tau |\hat{y}_i - y_i| &amp;amp; \text{if } |y - \hat{y}| \le \delta \\\\
  (1-\tau)|\hat{y}_i - y_i| &amp;amp; \text{otherwise}
\end{cases}
$$&lt;/div&gt;
&lt;p&gt; 
🗒️ An extension of MAE that applies different penalties to overestimation and underestimation based on a chosen quantile &lt;span class="math"&gt;\(\tau\)&lt;/span&gt; (between 0 and 1). Used for predicting prediction intervals rather than a single mean.&lt;br&gt;
💡 "I don't just want the average outcome, I want to be 90% sure the real value is below my prediction line." &lt;br&gt;
✅ Allows for uncertainty estimation and construction of confidence intervals.&lt;br&gt;
❌ More difficult to train, convergence can be slower than standard MSE/MAE.  &lt;/p&gt;
&lt;h3&gt;D1b. Geometry-aware (bounding boxes)&lt;/h3&gt;
&lt;p&gt;In object detection tasks, the goal of bounding box regression is to achieve geometric alignment between the predicted box and the ground truth. Unlike magnitude-based losses, geometric losses do not treat coordinates in isolation; instead, they view the box as a unified geometric entity, optimizing the spatial relationship (overlap, distance, and shape) between the prediction and the ground truth.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;IoU (Intersection over Union)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{IoU} = 1 - \frac{|B \cap B^{gt}|}{|B \cup B^{gt}|} $$&lt;/div&gt;
&lt;p&gt;
🗒️ Measures the overlap area between the predicted box &lt;span class="math"&gt;\(B\)&lt;/span&gt; and the ground truth box &lt;span class="math"&gt;\(B^{gt}\)&lt;/span&gt; divided by their union area.&lt;br&gt;
💡 "I don't care where the pixels are exactly, just make sure the two squares overlap as much as possible." &lt;br&gt;
✅ Invariant to the scale of the problem (a small box and large box with same overlap % have same loss).&lt;br&gt;
❌ If boxes do not overlap: IoU is 0, the gradient is 0, and the model stops learning completely.&lt;br&gt;
❌ If boxes overlap completely: IoU is 1, and the gradient becomes 0 again.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;GIoU (Generalized IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{GIoU} = 1 - IoU + \frac{|C \setminus (B \cup B^{gt})|}{|C|} $$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(C\)&lt;/span&gt; is the smallest convex box covering both &lt;span class="math"&gt;\(B\)&lt;/span&gt; and &lt;span class="math"&gt;\(B^{gt}\)&lt;/span&gt;.&lt;br&gt;
🗒️ Adds a penalty term based on the empty space within the smallest enclosing box &lt;span class="math"&gt;\(C\)&lt;/span&gt;. This ensures gradients exist even when boxes do not overlap.&lt;br&gt;
💡 "If the boxes aren't touching, move the prediction towards the target to minimize the empty space between them." &lt;br&gt;
✅ Solves the vanishing gradient problem of standard IoU for non-overlapping boxes.&lt;br&gt;
❌ Does not solve the vanishing gradient problem of standard IoU for completely-overlapping boxes.&lt;br&gt;
❌ Convergence is slow, it tends to expand the predicted box to cover the target first before shrinking to fit.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;DIoU (Distance IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{DIoU} = 1 - IoU + \frac{\rho^2(b, b^{gt})}{c^2} $$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(\rho\)&lt;/span&gt; is Euclidean distance, &lt;span class="math"&gt;\(b\)&lt;/span&gt; and &lt;span class="math"&gt;\(b^{gt}\)&lt;/span&gt; are the center points, and &lt;span class="math"&gt;\(c\)&lt;/span&gt; is the diagonal length of the enclosing box. &lt;br&gt;
🗒️ Adds a penalty minimizing the normalized distance between the center points of the two boxes.&lt;br&gt;
💡 "Don't just overlap, aim for the bullseye. Align the centers of the boxes directly." &lt;br&gt;
✅ Converges much faster than GIoU because it minimizes distance directly rather than area.&lt;br&gt;
✅ Completely solves the vanishing gradient problem.&lt;br&gt;
❌ Does not consider the aspect ratio of the boxes.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;CIoU (Complete IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{CIoU} = 1 - IoU + \frac{\rho^2(b, b^{gt})}{c^2} + \alpha v$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(v\)&lt;/span&gt; measures aspect ratio consistency and &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; is a weighting parameter.&lt;br&gt;
🗒️ Extends DIoU by adding a term to ensure the aspect ratio of the prediction matches the target.&lt;br&gt;
💡 "Overlap, hit the center, and make sure you aren't drawing a tall rectangle when it should be a wide one." &lt;br&gt;
✅ Considers all geometric factors: overlap area, central point distance, and aspect ratio.&lt;br&gt;
❌ The aspect ratio term &lt;span class="math"&gt;\(v\)&lt;/span&gt; is complex and gradients can sometimes be unstable depending on the implementation.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;EIoU (Efficient IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{EIoU} = 1 - IoU + \frac{\rho^2(b, b^{gt})}{c^2} + \frac{\rho^2(w, w^{gt})}{C_w^2} + \frac{\rho^2(h, h^{gt})}{C_h^2}$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(w,h\)&lt;/span&gt; are width/height and &lt;span class="math"&gt;\(C_w, C_h\)&lt;/span&gt; are the width/height of the enclosing box.&lt;br&gt;
🗒️ Improves CIoU by splitting the aspect ratio term into separate penalties for width and height differences.&lt;br&gt;
💡 "CIoU was a bit messy with the shape math. Let's just strictly measure the width error and the height error separately." &lt;br&gt;
✅ Faster convergence and better localization accuracy than CIoU.&lt;br&gt;
✅ Solves the ambiguity in CIoU where different &lt;span class="math"&gt;\(w/h\)&lt;/span&gt; pairs could produce the same aspect ratio penalty.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;SIoU (Scylla-IoU)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{SIoU} = 1 - IoU + \frac{\Delta + \Omega}{2}$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(\Delta\)&lt;/span&gt; is the distance cost and &lt;span class="math"&gt;\(\Omega\)&lt;/span&gt; is the shape cost.&lt;br&gt;
🗒️ Introduces an angle cost to the regression. It considers the vector angle between the center of the predicted box and the ground truth. It prioritizes aligning the box to the nearest axis (X or Y) to minimize freedom of movement.&lt;br&gt;
💡 "Stop wandering around diagonally! Move strictly horizontal or vertical to line up with the target first, then adjust the size." &lt;br&gt;
✅ Converges faster than CIoU and EIoU by reducing the oscillation of the box during training.&lt;br&gt;
❌ Computationally slightly heavier due to the calculation of trigonometric (inverse sine) components.  &lt;/p&gt;
&lt;h2&gt;D2. Classification losses (discrete)&lt;/h2&gt;
&lt;p&gt;Classification is a subset of supervised learning tasks where the goal is to assign an input &lt;span class="math"&gt;\(x\)&lt;/span&gt; to one of &lt;span class="math"&gt;\(K\)&lt;/span&gt; discrete classes.&lt;/p&gt;
&lt;h3&gt;D2a. Margin-based (decision boundaries)&lt;/h3&gt;
&lt;p&gt;Margin losses introduce a threshold parameter to enforce a minimal separation between the predicted score and the correct class. They compel the model to not just classify correctly, but to do so with high confidence by maintaining a 'safe distance' from the decision boundary.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Hinge&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Hinge} = \max(0, 1 - y_i \hat{y}_i)$$&lt;/div&gt;
&lt;p&gt;
🗒️ The standard loss for Support Vector Machines (SVMs). It only penalizes the model if the correct class score is not sufficiently higher than the margin. If the prediction is correct and confident (&lt;span class="math"&gt;\(y \hat{y} \ge 1\)&lt;/span&gt;), the loss is zero.&lt;br&gt;
💡 "I don't just want you to be right, I want you to be right by a wide margin. If you barely squeak past the finish line, I'm still giving you a penalty." &lt;br&gt;
✅ Points that are correctly classified with high confidence have 0 gradients and do not affect the model update, saving computation.&lt;br&gt;
❌ The function is non-differentiable at &lt;span class="math"&gt;\(y\hat{y}=1\)&lt;/span&gt;, requiring sub-gradient optimization methods.&lt;br&gt;
↔️ Variant Squared Hinge: Differentiable but still sensitive to outliers.&lt;br&gt;
↔️ Variant Quadratic Smoothed Hinge: Linear for large errors to keep robustness, and quadratic near the margin boundary to ensure differentiability.&lt;br&gt;
↔️ Variant Ramp: Caps the loss to ignore extreme outliers.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Exponential&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Exp} = e^{-y_i \hat{y}_i}$$&lt;/div&gt;
&lt;p&gt;
🗒️ Primarily used in boosting algorithms like AdaBoost. It applies an exponential penalty to negative margins (incorrect classifications).&lt;br&gt;
💡 "If you get a difficult example wrong, the penalty will be massive. You must obsess over the hardest data points." &lt;br&gt;
✅ Forces the model to focus intensely on the examples it is currently getting wrong.&lt;br&gt;
✅ Differentiable and convex.&lt;br&gt;
❌ Because the penalty grows exponentially, a single mislabeled outlier can dominate the gradient and ruin the training process.  &lt;/p&gt;
&lt;h3&gt;D2b. Probabilistic (distribution divergence)&lt;/h3&gt;
&lt;p&gt;Let &lt;span class="math"&gt;\(q\)&lt;/span&gt; be the true probability distribution of the dataset and &lt;span class="math"&gt;\(p_{\theta}\)&lt;/span&gt; be the predicted distribution generated by the model. Probabilistic loss functions measure the divergence (distance) between &lt;span class="math"&gt;\(q\)&lt;/span&gt; and &lt;span class="math"&gt;\(p_{\theta}\)&lt;/span&gt;. By minimizing this divergence, the model's output distribution converges toward the ground truth.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;CE (Cross-Entropy)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{CE} = -\frac{1}{N} \sum_{i=1}^{N} \sum_{k=1}^{K} y_{i,k} \log(\hat{y}_{i,k})$$&lt;/div&gt;
&lt;p&gt;
🗒️ Measures the information difference between the predicted distribution and the true distribution. When targets are one-hot encoded, minimizing CE is mathematically equivalent to maximizing the likelihood of the correct class.&lt;br&gt;
💡 "If the image is a cat, I want the probability of 'cat' to be 1.0. Every bit of probability mass assigned to 'dog' or 'bird' increases the penalty." &lt;br&gt;
✅ The default loss for classification, differentiable and rigorous strictly based on Information Theory.&lt;br&gt;
❌ Dominated by majority classes if data is unbalanced.&lt;br&gt;
❌ Dominated by easy examples (background) in dense detection tasks.&lt;br&gt;
↔️ Variant Weighted CE: Multiplies the loss of class &lt;span class="math"&gt;\(k\)&lt;/span&gt; by a weight &lt;span class="math"&gt;\(\alpha_k\)&lt;/span&gt; (usually inverse to class frequency or the effective number of samples).&lt;br&gt;
↔️ Variant Label Smoothing: Changes target &lt;span class="math"&gt;\(y=1\)&lt;/span&gt; to &lt;span class="math"&gt;\(y=1-\epsilon\)&lt;/span&gt; and &lt;span class="math"&gt;\(y=0\)&lt;/span&gt; to &lt;span class="math"&gt;\(y=\frac{\epsilon}{K-1}\)&lt;/span&gt; to prevent overfitting.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Focal&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Focal} = -\frac{1}{N} \sum_{i=1}^{N} \alpha (1 - \hat{p}_i)^\gamma \log(\hat{p}_i)$$&lt;/div&gt;
&lt;p&gt;
🗒️ Adds a modulating factor &lt;span class="math"&gt;\((1 - \hat{p}_i)^\gamma\)&lt;/span&gt; to standard Cross-Entropy. If a sample is already well-classified (e.g., &lt;span class="math"&gt;\(\hat{p}_i = 0.9\)&lt;/span&gt;), the factor approaches 0, effectively silencing the loss for that example.&lt;br&gt;
💡 "I don't care about the background sky that you've already correctly identified 1,000 times. Focus entirely on that one difficult pixel that looks like a pedestrian." &lt;br&gt;
✅ Solves the class imbalance problem without manual oversampling.&lt;br&gt;
✅ The standard for dense object detection.&lt;br&gt;
❌ Requires tuning two hyperparameters (&lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; and &lt;span class="math"&gt;\(\gamma\)&lt;/span&gt;) which can be sensitive to the dataset.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;GHM (Gradient Harmonized Mechanism)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{GHM} = \sum_{i=1}^{N} \frac{L_{CE}}{GD(g_i)}$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(g_i\)&lt;/span&gt; is the gradient norm and &lt;span class="math"&gt;\(GD\)&lt;/span&gt; is the gradient density (a measure of how many samples have that same gradient).&lt;br&gt;
🗒️ An advanced alternative to Focal loss. It observes that easy examples and outliers both have distinct gradient behaviors. It harmonizes training by normalizing the loss based on the density of gradients. If a million examples produce the same small gradient (easy background), their contribution is divided by a large density factor.&lt;br&gt;
💡 "If everyone else is shouting the same thing, I'm going to turn down the volume on that group. I only want to hear the unique/rare errors." &lt;br&gt;
✅ Does not require manual tuning of &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; or &lt;span class="math"&gt;\(\gamma\)&lt;/span&gt; like Focal loss, it adapts to the training data dynamics.&lt;br&gt;
❌ The computational cost increases: it requires calculating a histogram of gradients across the batch/dataset during training.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Poly&lt;/strong&gt;  &lt;/p&gt;
&lt;div class="math"&gt;$$
L_{Poly} = -\sum_{j=1}^{\infty} \alpha_j (1 - \hat{p}_t)^j 
$$&lt;/div&gt;
&lt;p&gt;🗒️ Views Cross-Entropy as a Taylor series expansion and generalizes it, allowing for the adjustment of the leading polynomial coefficients &lt;span class="math"&gt;\(\alpha_j\)&lt;/span&gt; to structurally change how the loss behaves (instead of having it fixed at &lt;span class="math"&gt;\(1/j\)&lt;/span&gt;). In practice, usually only the leading coefficient (&lt;span class="math"&gt;\(\epsilon_1\)&lt;/span&gt;) is modified: &lt;span class="math"&gt;\(L_{Poly1} = L_{CE} + \epsilon_1 (1 - \hat{p}_t)\)&lt;/span&gt;.&lt;br&gt;
💡 "Cross-Entropy is a fixed curve, but we can reshape it if we need to." &lt;br&gt;
✅ Generalized framework that encompasses Cross-Entropy and Focal Loss as special cases.&lt;br&gt;
✅ Poly-1 often outperforms Focal/CE by tuning a single parameter, with negligible additional computational cost.&lt;br&gt;
❌ Introduces a non-standard hyperparameter that must be found via grid search, as there is no universal default.  &lt;/p&gt;
&lt;h3&gt;D2c. Overlap-based (segmentation)&lt;/h3&gt;
&lt;p&gt;In semantic segmentation, classification occurs at the pixel level. However, pixel-wise losses often struggle when the target object occupies only a small fraction of the image. Overlap-based losses address this by directly optimizing the intersection between the predicted segmentation map and the ground truth, prioritizing global shape alignment over individual pixel accuracy.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tversky&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Tversky} = 1 - \frac{\sum \hat{y} y}{\sum \hat{y} y + \alpha \sum (1-y)\hat{y} + \beta \sum y(1-\hat{y})}$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(y\)&lt;/span&gt; is the target, &lt;span class="math"&gt;\(\hat{y}\)&lt;/span&gt; is the prediction, &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; controls penalty for false positives, and &lt;span class="math"&gt;\(\beta\)&lt;/span&gt; controls penalty for false negatives.&lt;br&gt;
🗒️ A generalization of the Dice coefficient (when &lt;span class="math"&gt;\(\alpha = \beta = 0.5\)&lt;/span&gt;). Allows the shifting of the balance between precision (avoiding false positives) and recall (avoiding false negatives).&lt;br&gt;
💡 "If finding the tumor is critical and we cannot afford to miss it, set &lt;span class="math"&gt;\(\beta\)&lt;/span&gt; higher than &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; to punish missing pixels more than extra ones." &lt;br&gt;
✅ Much better than Cross-Entropy at imbalance handling for small objects.&lt;br&gt;
✅ Parameters &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; and &lt;span class="math"&gt;\(\beta\)&lt;/span&gt; give flexibility to tune the trade-off based on clinical or business needs.&lt;br&gt;
❌ Can be unstable during the early stages of training compared to pixel-wise CE.&lt;br&gt;
↔️ Variant Focal Tversky: Applies the mechanism of Focal loss to the Tversky index.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sensitivity-Specificity&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{SS} = w \cdot \frac{\sum (y-\hat{y})^2 y}{\sum y} + (1-w) \cdot \frac{\sum (y-\hat{y})^2 (1-y)}{\sum (1-y)}$$&lt;/div&gt;
&lt;p&gt;
🗒️ Explicitly optimizes the weighted sum of the squared errors for the positive class (sensitivity) and the negative class (specificity). It ensures the model does not achieve high accuracy by simply ignoring the background or the foreground.&lt;br&gt;
💡 "I need you to be good at finding the object, but equally good at NOT finding the object where it doesn't exist. Balance your excitement." &lt;br&gt;
✅ Addresses both over-segmentation (too much background included) and under-segmentation (missing parts of the object).&lt;br&gt;
✅ Appropriate for medical contexts where specificity is just as vital as sensitivity.&lt;br&gt;
❌ Highly sensitive to the weight parameter &lt;span class="math"&gt;\(w\)&lt;/span&gt;. If set incorrectly, the model may collapse into predicting only the background or only the foreground.  &lt;/p&gt;
&lt;h2&gt;D3. Metric losses (embedding space)&lt;/h2&gt;
&lt;p&gt;The goal of metric learning is to learn the relative distances between inputs rather than predicting a specific label or value. Metric loss functions operate on pairs (or triplets) of data instances, extracting an embedded representation for each. A distance metric measures the similarity between these representations. The model is trained to minimize the distance between representations of similar inputs and maximize the distance between dissimilar ones, structuring the embedding space meaningfully.&lt;/p&gt;
&lt;h3&gt;D3a. Euclidean distance&lt;/h3&gt;
&lt;p&gt;These losses directly use geometric distance in the embedding space as the optimization target.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Contrastive Loss&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Contrastive} = \frac{1}{2} \sum_{i=1}^{N} [Y_iD_i^2 + (1-Y_i) \max(0, m - D_i)^2]$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(D = ||f(x_1) - f(x_2)||_2\)&lt;/span&gt; is the Euclidean distance between the pair of samples, &lt;span class="math"&gt;\(Y=1\)&lt;/span&gt; implies same class, &lt;span class="math"&gt;\(Y=0\)&lt;/span&gt; implies different class, and &lt;span class="math"&gt;\(m\)&lt;/span&gt; is the margin.&lt;br&gt;
🗒️ Takes pairs of samples. If they belong to the same class, it minimizes their distance. If they belong to different classes, it pushes them apart until they are at least margin &lt;span class="math"&gt;\(m\)&lt;/span&gt; away.&lt;br&gt;
💡 "If you are twins, hug each other. If you are strangers, push away until you have at least 1 meter of personal space between you." &lt;br&gt;
✅ Is the simple foundational approach to metric learning.&lt;br&gt;
❌ Hard to tune the margin. If &lt;span class="math"&gt;\(m\)&lt;/span&gt; is too small, clusters overlap; if too large, training becomes unstable.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Triplet&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Triplet} = \sum_{i=1}^{N} \max(0, D(a_i, p_i)^2 - D(a_i, n_i)^2 + m)$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(a\)&lt;/span&gt; is anchor, &lt;span class="math"&gt;\(p\)&lt;/span&gt; is positive (same class), &lt;span class="math"&gt;\(n\)&lt;/span&gt; is negative (different class), and &lt;span class="math"&gt;\(m\)&lt;/span&gt; is margin.&lt;br&gt;
🗒️ Takes three samples at once: an anchor, a positive, and a negative. It ensures that the anchor is closer to the positive than it is to the negative by at least margin &lt;span class="math"&gt;\(m\)&lt;/span&gt;.&lt;br&gt;
💡 "I don't care exactly where the anchor is located, as long as its friend (positive) is closer to it than its enemy (negative)." &lt;br&gt;
✅ More flexible than Contrastive loss because it relaxes the constraint on absolute distances, only the relative ranking matters.&lt;br&gt;
❌ Requires finding negatives that are currently closer than positives. If random negatives are picked, the loss is usually 0 and the model learns nothing.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;InfoNCE (Information Noise-Contrastive Estimation)&lt;/strong&gt;&lt;br&gt;
🗒️ It treats the task as a classification problem: "Among this batch of &lt;span class="math"&gt;\(K\)&lt;/span&gt; negatives and 1 positive, identify the positive." It maximizes the mutual information between the query and the positive key.&lt;br&gt;
💡 "Here is one photo of a dog and 1,000 photos of other things. Can you pick the correct dog out of this lineup?" &lt;br&gt;
✅ Learns from one positive and many negatives simultaneously, providing a much richer gradient signal than Triplet.&lt;br&gt;
✅ It is the standard backbone for modern self-supervised representation learning.&lt;br&gt;
❌ Often requires very large batch sizes (to have enough hard negatives) to work effectively.  &lt;/p&gt;
&lt;h3&gt;D3b. Angular margin&lt;/h3&gt;
&lt;p&gt;Losses based on angular or cosine margins do not directly optimize absolute position and distance on the feature space. Instead, they focus on the angular boundaries between classes by projecting features onto a hypersphere and optimizing the cosine similarity between feature vectors and class centers.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A-Softmax (Angular Softmax / SphereFace)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Sphere} = -\log \frac{e^{||x_i|| \psi(\theta_{y_i})}}{e^{||x_i|| \psi(\theta_{y_i})} + \sum_{j \neq y_i} e^{||x_i|| \cos(\theta_j)}}$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(\psi(\theta)\)&lt;/span&gt; is a monotonic function replacing &lt;span class="math"&gt;\(\cos(\theta)\)&lt;/span&gt; with &lt;span class="math"&gt;\(\cos(m\theta)\)&lt;/span&gt;.&lt;br&gt;
🗒️ The first major angular loss. It introduces a multiplicative angular margin &lt;span class="math"&gt;\(m\)&lt;/span&gt;, and forces the angle of the correct class to be &lt;span class="math"&gt;\(m\)&lt;/span&gt; times smaller than the angle of any incorrect class.&lt;br&gt;
💡 "If the angle to your class center is 10 degrees, I will pretend it is actually 40 degrees (&lt;span class="math"&gt;\(m=4\)&lt;/span&gt;). You have to work 4 times harder to prove you belong there." &lt;br&gt;
✅ Pioneered the concept of angular margins, proving that geometric constraints on the hypersphere significantly improve feature discrimination.&lt;br&gt;
❌ The optimization is difficult and requires complex annealing of the hyperparameter &lt;span class="math"&gt;\(\lambda\)&lt;/span&gt; to converge.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;AM-Softmax (Additive Margin Softmax / CosFace)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Cos} = -\log (\frac{e^{s(\cos(\theta_{y_i}) - m)}}{e^{s(\cos(\theta_{y_i}) - m)} + \sum_{j \neq y_i} e^{s \cos(\theta_j)}})$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(s\)&lt;/span&gt; is a scale factor and &lt;span class="math"&gt;\(m\)&lt;/span&gt; is an additive cosine margin.&lt;br&gt;
🗒️ Simplifies SphereFace by moving the margin &lt;span class="math"&gt;\(m\)&lt;/span&gt; outside the cosine function. It subtracts a margin &lt;span class="math"&gt;\(m\)&lt;/span&gt; directly from the cosine similarity value.&lt;br&gt;
💡 "Standard Softmax is too lenient. I'm going to subtract 0.3 from your similarity score. You effectively need a score of 1.3 to get a perfect 1.0. Push harder!" &lt;br&gt;
✅ Much easier to implement and train than SphereFace.&lt;br&gt;
✅ It is more interpretable as it directly optimizes cosine similarity gap.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Additive Angular Margin (ArcFace)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Arc} = -\log (\frac{e^{s \cos(\theta_{y_i} + m)}}{e^{s \cos(\theta_{y_i} + m)} + \sum_{j \neq y_i} e^{s \cos(\theta_j)}})$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(m\)&lt;/span&gt; is an additive angular margin added inside the cosine.&lt;br&gt;
🗒️ It adds the margin &lt;span class="math"&gt;\(m\)&lt;/span&gt; inside the cosine term, which corresponds to a direct geodesic distance penalty on the hypersphere.&lt;br&gt;
💡 "Imagine the classes are countries on a globe. ArcFace draws strict borders with a 'No Man's Land' buffer zone between every country directly on the surface of the sphere." &lt;br&gt;
✅ The margin has a constant correspondence to arc length on the hypersphere.&lt;br&gt;
✅ Is the state-of-the-art for face recognition.&lt;br&gt;
❌ Requires careful tuning of scale &lt;span class="math"&gt;\(s\)&lt;/span&gt; and margin &lt;span class="math"&gt;\(m\)&lt;/span&gt; depending on dataset noise.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Quality Adaptive Margin Softmax (AdaFace)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Ada} = -\log (\frac{e^{s \cos(\theta_{y_i} + g_{angle})}}{e^{s \cos(\theta_{y_i} + g_{angle})} + \sum_{j \neq y_i} e^{s \cos(\theta_j)}})$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(g_{angle}\)&lt;/span&gt; is a margin function that adapts based on the image quality (feature norm &lt;span class="math"&gt;\(||\hat{z}_i||\)&lt;/span&gt;).&lt;br&gt;
🗒️ Adapts the margin based on the quality of the input image. It applies a strict margin to high-quality images and a relaxed margin to low-quality images to prevent the model from overfitting to noise.&lt;br&gt;
💡 "If the photo is HD, I expect perfection. If the photo is a blurry CCTV frame, I'll go easy on you so you don't get confused trying to learn noise." &lt;br&gt;
✅ State-of-the-art for unconstrained face recognition (e.g., surveillance, low resolution).&lt;br&gt;
✅ Prevents the model from getting stuck trying to optimize unrecognizably bad samples.&lt;br&gt;
❌ Introduces complexity in implementation and relies on the assumption that feature norm correlates with image quality (which is usually true, but not always).  &lt;/p&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h1&gt;Generative tasks&lt;/h1&gt;
&lt;p&gt;Optimize for &lt;span class="math"&gt;\(P(X)\)&lt;/span&gt; or &lt;span class="math"&gt;\(P(X,Y)\)&lt;/span&gt;. Losses for these tasks focus on learning the underlying data distribution to generate new samples or reconstruct inputs. These objective functions are often composite, blending multiple terms (reconstruction, distribution matching, perceptual quality) to achieve realistic results.&lt;/p&gt;
&lt;h2&gt;G1. Reconstruction terms (element-wise)&lt;/h2&gt;
&lt;p&gt;These terms ensure fidelity by measuring the direct difference between the original input &lt;span class="math"&gt;\(x\)&lt;/span&gt; and the reconstructed/generated output &lt;span class="math"&gt;\(\hat{x}\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;MSE (Mean Squared Error)&lt;/strong&gt;&lt;br&gt;
🗒️ Is the same function used for discriminative tasks. For generative tasks, this acts as the "fidelity" term.&lt;br&gt;
💡 "The generated image must look exactly like the input, pixel by pixel." &lt;br&gt;
✅ Simple to implement and theoretically guarantees the highest PSNR (Peak Signal-to-Noise Ratio).&lt;br&gt;
❌ In generative contexts, pure MSE tends to produce blurry images because it averages out high-frequency details.  &lt;/p&gt;
&lt;h2&gt;G2. Distribution matching terms (divergences)&lt;/h2&gt;
&lt;p&gt;These terms minimize the statistical discrepancy between the learned generated distribution &lt;span class="math"&gt;\(P_g\)&lt;/span&gt; and the real data distribution &lt;span class="math"&gt;\(P_{data}\)&lt;/span&gt;. They are central to GANs and Variational Autoencoders (VAEs).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Minimax (GAN loss)&lt;/strong&gt;&lt;br&gt;
🗒️ A zero-sum game between two networks: a generator (&lt;span class="math"&gt;\(G\)&lt;/span&gt;) tries to fool the discriminator, and a discriminator (&lt;span class="math"&gt;\(D\)&lt;/span&gt;) tries to distinguish real from fake.&lt;br&gt;
💡 "Generator: I bet I can trick you. Discriminator: No you can't, I'll spot the fake." &lt;br&gt;
✅ Produces very sharp, realistic details compared to MSE.&lt;br&gt;
❌ Very difficult to train.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Wasserstein Distance (WGAN loss)&lt;/strong&gt;&lt;br&gt;
🗒️ It calculates the minimum "work" (mass × distance) required to transform one distribution into another. Unlike the standard GAN loss, the discriminator (now called critic) outputs a raw score, not a probability.&lt;br&gt;
💡 "Instead of asking 'True or False?', better ask 'How real is this?' to let the generator exactly know how far it is from the target, even if it's currently failing completely." &lt;br&gt;
✅ Provides meaningful gradients even when the real and fake distributions do not overlap at all, solving the vanishing gradient problem of standard GANs.&lt;br&gt;
✅ The loss value correlates linearly with the visual quality of the generated images, which is not true for standard GAN loss.&lt;br&gt;
❌ Requires enforcing 1-Lipschitz continuity (the gradient cannot change too fast), which is difficult to implement (requires weight clipping or gradient penalties).  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;KL (Kullback-Leibler Divergence)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{KL} = \sum P(x) \log (\frac{P(x)}{Q(x)}) $$&lt;/div&gt;
&lt;p&gt;
🗒️ Measures how much information is lost when distribution &lt;span class="math"&gt;\(Q\)&lt;/span&gt; is used to approximate &lt;span class="math"&gt;\(P\)&lt;/span&gt;. In VAEs, it forces the learned latent space to follow a standard Gaussian distribution.&lt;br&gt;
💡 "Keep your latent code organized like a standard bell curve so we can sample from it easily later." &lt;br&gt;
✅  Forces the learned latent variables to follow a tractable distribution (usually Unit Gaussian), ensuring the latent space is smooth and continuous.&lt;br&gt;
❌ The strict Gaussian constraint often results in over-regularized and blurry outputs.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sinkhorn Divergence&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$L_{Sinkhorn} = \min_{\pi} \sum_{i,j} C_{i,j} \pi_{i,j} + \epsilon H(\pi)$$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(C\)&lt;/span&gt; is the cost matrix, &lt;span class="math"&gt;\(\pi\)&lt;/span&gt; is the transport plan, and &lt;span class="math"&gt;\(H\)&lt;/span&gt; is regularization entropy.&lt;br&gt;
🗒️ Adds an entropic regularization term to the optimal transport problem. This allows the Wasserstein distance to be computed much faster using the Sinkhorn-Knopp algorithm.&lt;br&gt;
💡 "Calculating the perfect earth-moving plan is hard. If we allow a little bit of randomness in where the dirt goes, we can solve the math 100x faster." &lt;br&gt;
✅ Differentiable and computationally fast enough to be used as a loss function.&lt;br&gt;
❌ If &lt;span class="math"&gt;\(\epsilon\)&lt;/span&gt; is too large, the metric becomes too blurry and loses the geometric accuracy of the true Wasserstein distance.  &lt;/p&gt;
&lt;h2&gt;G3. Diffusion terms (noise removal)&lt;/h2&gt;
&lt;p&gt;Used in Diffusion Probabilistic Models (DDPMs). The goal is to reverse a gradual noising process.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Simple Diffusion&lt;/strong&gt; &lt;br&gt;
🗒️ The model predicts the noise &lt;span class="math"&gt;\(\epsilon\)&lt;/span&gt; that was added to the image &lt;span class="math"&gt;\(x_0\)&lt;/span&gt; at timestep &lt;span class="math"&gt;\(t\)&lt;/span&gt;.&lt;br&gt;
💡 "I will show you a noisy TV screen. You tell me exactly which pixels are noise so I can subtract them and reveal the image underneath." &lt;br&gt;
✅ Training is essentially a massive set of regression tasks (MSE on noise), which is a lot more stable compared to GANs.&lt;br&gt;
❌ Inference is slow, as generating a single image requires running the network iteratively (e.g., 50 to 1000 times) to denoise the output step-by-step.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Denoising Score Matching&lt;/strong&gt;&lt;br&gt;
🗒️ Optimizes the model to estimate the score function (the gradient of the log-density of the data). By moving along the gradient, you move from a noisy data point toward the clean data manifold.&lt;br&gt;
💡 "You are dropped in a foggy forest. You don't know where the mountain peak is, but if you just look at your feet and step where the ground slopes upward, you will eventually get there." &lt;br&gt;
✅ Bypasses the intractable problem of calculating the normalizing constant of the probability distribution.&lt;br&gt;
❌ Technically complex to derive and implement compared to the simplified objective used in practical Simple Diffusion.  &lt;/p&gt;
&lt;h2&gt;G4. Auxiliary guidance terms (feature-based)&lt;/h2&gt;
&lt;p&gt;Instead of comparing raw pixels, these losses compare high-level representations extracted by a pre-trained network.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Perceptual&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{Perc} = || \phi(x) - \phi(\hat{x}) ||_2^2 $$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(\phi\)&lt;/span&gt; is a pre-trained feature extractor.&lt;br&gt;
🗒️ Compares the internal activation maps of a pre-trained network for the real and generated images.&lt;br&gt;
💡 "I don't care if the exact pixel matches. Does the image look like a dog? Do the edges and textures match human perception?" &lt;br&gt;
✅ Correlates much better with human visual judgment than MSE, and provides excellent textures for style transfer and super-resolution.&lt;br&gt;
❌ Relies on pre-trained networks, so it may fail or produce artifacts if the target domain is vastly different.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Style&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="math"&gt;$$ L_{Style} = || G(\phi(x)) - G(\phi(\hat{x})) ||_F^2 $$&lt;/div&gt;
&lt;p&gt;
Where &lt;span class="math"&gt;\(G\)&lt;/span&gt; computes the Gram Matrix—correlations between features.&lt;br&gt;
🗒️ Measures the correlation between different feature channels. It captures "style" (texture, brushstrokes, color patterns) while discarding spatial structure.&lt;br&gt;
💡 "Capture the vibe of Van Gogh but don't worry about where the trees are actually located." &lt;br&gt;
✅ Explicitly decouples texture from structure, allowing for the synthesis of complex artistic patterns without needing paired training data.&lt;br&gt;
❌ Does not enforce spatial coherence, so texture patches can appear in semantically incorrect locations (e.g., brushstrokes appearing in the sky instead of the trees).  &lt;/p&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (true) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=TeX-AMS-MML_HTMLorMML';

    var configscript = document.createElement('script');
    configscript.type = 'text/x-mathjax-config';
    configscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'none'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        availableFonts: ['STIX', 'TeX']," +
        "        preferredFont: 'STIX'," +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";

    (document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="Deep Learning"></category></entry><entry><title>Plataforma Weights &amp; Biases</title><link href="https://facuroffet99.github.io/notes/mlops_1.html" rel="alternate"></link><published>2025-08-04T12:15:00-03:00</published><updated>2025-08-04T12:15:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-08-04:/notes/mlops_1.html</id><summary type="html">&lt;p&gt;Notas personales sobre la plataforma Weights &amp;amp; Biases: tracking de experimentos, Model Registry, W&amp;amp;B Weave para LLMs y pipeline de buenas prácticas.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Plataforma Weights &amp; Biases&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;Estas son mis notas personales de los cursos &lt;a href="https://wandb.ai/site/courses/101/"&gt;Weights &amp;amp; Biases 101&lt;/a&gt;, &lt;a href="https://www.wandb.courses/courses/201-model-registry"&gt;Weights &amp;amp; Biases 201: Model Registry&lt;/a&gt;, &lt;a href="https://wandb.ai/site/courses/weave/"&gt;Weights &amp;amp; Biases 101: Weave&lt;/a&gt; y &lt;a href="https://wandb.ai/site/courses/effective-mlops/"&gt;Effective MLOps: Model development&lt;/a&gt;. &lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Entrenar modelos de IA: W&amp;amp;B Models&lt;/h2&gt;
&lt;h4&gt;Runs&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Una Run es una unidad de ejecución de código Python, que captura todo su contexto (versiones de librerías, hardware, métricas del sistema, estado de Git, etc).&lt;/li&gt;
&lt;li&gt;Puede incluir varios tipos de logs: métricas escalares, media (imágenes, histogramas, visualizaciones 3D, videos, audio), gráficos, tablas, etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Projects&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Un Project contine múltiples Runs y todos sus datos asociados.&lt;/li&gt;
&lt;li&gt;En la GUI, un Project tiene distintas pestañas:&lt;ul&gt;
&lt;li&gt;Overview: información general.&lt;/li&gt;
&lt;li&gt;Workspace: dashboard interactivo con paneles personalizables para visualizar resultados y comparar distintos Runs.&lt;/li&gt;
&lt;li&gt;Runs: tabla que lista todas las Runs del Project.&lt;/li&gt;
&lt;li&gt;Automations: procesos automáticos configurados.&lt;/li&gt;
&lt;li&gt;Sweeps: conjunto de Runs que prueban automáticamente distintos hiperparámetros.&lt;/li&gt;
&lt;li&gt;Reports: documentos flexibles e interactivos que se actualizan automáticamente, que sirve para compartir visualizaciones de un Project.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Artifacts&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Un Artifact permite rastrear y versionar cualquier dato que sea usado como entrada o salida de una Run: datasets, resultados de evaluación o checkpoints de modelos. Encapsula tanto archivos como carpetas, y se compone de:&lt;ul&gt;
&lt;li&gt;Un nombre&lt;/li&gt;
&lt;li&gt;Un tipo (los más útiles son 'dataset' y 'model')&lt;/li&gt;
&lt;li&gt;Metadatos (en forma de diccionario)&lt;/li&gt;
&lt;li&gt;Una descripción&lt;/li&gt;
&lt;li&gt;Archivos, carpetas o referencias a almacenes externos de objetos (ej: s3)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Cada vez que se registra un Artifact con el mismo nombre, es comparado con sus versiones anteriores. Si hay alguna diferencia, se crea una nueva versión indicada con un alias (v1, v2, v3).&lt;/li&gt;
&lt;li&gt;En la GUI de W&amp;amp;B se pueden ver datos de la versión, los metadatos, los archivos contenidos, el linaje (árbol genealógico con los procesos que crearon o usaron al Artifact) y un código de uso rápido.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Model Registry&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;El Model Registry es un repositorio centralizado que alberga y organiza distintas Collections (también llamadas Model Tasks).&lt;/li&gt;
&lt;li&gt;Dicho de otra forma, en el Model Registry conviven todos los modelos aptos para salir a la luz, ya sea para ser testeados o puestos en producción.&lt;/li&gt;
&lt;li&gt;Una Collection se refiere a una tarea en particular (segmentación de edificios, clasificación de células, etc). Contiene Artifacts de tipo 'model' que fueron promovidos como candidatos a ser usados por equipos o procesos posteriores. Opinión personal: cada Project debería tener una única Collection asociada.&lt;/li&gt;
&lt;li&gt;Una Collection puede contener varias versiones de un mismo modelo, a las que se les pueden asignar distintos alias. Por ejemplo: staging y production.&lt;/li&gt;
&lt;li&gt;En el Model Registry se pueden establecer Automations, que son acciones automáticas a ejecutar cuando se añade un nuevo modelo o un nuevo alias. Por ejemplo: crear un Report.&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Desarrollar aplicaciones con LLMs: W&amp;amp;B Weave&lt;/h2&gt;
&lt;h4&gt;Calls&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Las Calls son el bloque fundamental de Weave, y representan una única ejecución de una función incluyendo sus entradas (argumentos), salidas (retornos) y metadatos (tiempos, excepciones, etc).&lt;/li&gt;
&lt;li&gt;Una Call puede estar relacionada a otra por medio de una relación de padre o de hijo, formando una estructura de árbol.&lt;/li&gt;
&lt;li&gt;Una vez creada, una Call no puede ser modificada. Lo único que puede hacerse es agregarle feedback o eliminarla (tanto por medio de código o de la GUI).&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Traces&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Una Trace (o Span) es una colección de Calls que se encuentran en un mismo contexto de ejecución.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Objects (Models y Datasets) y Ops&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Un Object es un tipo de dato que Weave puede entender, serializar y versionar. Los Models y los Datasets son subclases de Objects; las Ops son funciones/métodos que actúan sobre Objects.&lt;/li&gt;
&lt;li&gt;Un Model sirve para versionar una app a lo largo del tiempo y entender cómo las modificaciones afectan a las respuestas. Están compuestos de una combinación de datos (configuración, checkpoint, etc) y códigos que definen como el modelo opera.&lt;/li&gt;
&lt;li&gt;Para crear un Model, se debe crear una clase que herede de &lt;code&gt;weave.Model&lt;/code&gt; que contenga definiciones de tipo en todos sus campos y un método llamado &lt;code&gt;invoke&lt;/code&gt; o &lt;code&gt;predict&lt;/code&gt; con el decorator de Weave.&lt;/li&gt;
&lt;li&gt;Cuando se cambian los parámetros que definen a un Model, los cambios se loggean y la versión del modelo se actualiza automáticamente.&lt;/li&gt;
&lt;li&gt;Un Dataset es una colección de ejemplos para evaluar a un Model.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Evaluations&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Una Evaluation evalúa el desempeño de un Model en un Dataset usando una lista especificada de métricas (funciones o Scorers).&lt;/li&gt;
&lt;li&gt;La latencia y la cantidad de tokens son métricas que loggean por defecto.&lt;/li&gt;
&lt;li&gt;En la GUI se pueden hacer comparaciones exhaustivas entre distintas Evaluations.&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Uso básico en código&lt;/h2&gt;
&lt;h4&gt;Instalación&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;pip install wandb weave
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Setup&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;wandb&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nn"&gt;weave&lt;/span&gt;
&lt;span class="n"&gt;wandb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;login&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nd"&gt;@weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;op&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# decorator for every function/method to track (automatically included in common LLM libraries)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Inicialización&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;run&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;wandb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;project&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;project_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entity&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;entity_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;job_type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;job_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;dict_with_configs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;project_name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# only needed when using weave as standalone&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Logs&lt;/h4&gt;
&lt;p&gt;Escalares y archivos:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;train/epoch&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;epoch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;train/train_loss&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;train_loss&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;val/val_loss&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;val_loss&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;val/accuracy&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;acc&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;log_model&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path_to_model_file&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# same as creating an Artifact of type &amp;#39;model&amp;#39;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Artifacts:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Log&lt;/span&gt;
&lt;span class="n"&gt;artifact&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;wandb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Artifact&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;artifact_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;artifact_type&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;artifact&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_file&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path_to_file&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;artifact&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_dir&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path_to_folder&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;log_artifact&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;artifact&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Retrieve&lt;/span&gt;
&lt;span class="n"&gt;artifact&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;use_artifact&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;artifact_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;artifact_version&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;artifact_dir&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;artifact&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;download&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Objects:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Log&lt;/span&gt;
&lt;span class="n"&gt;weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;publish&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;variable_to_log&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;log_name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Retrieve&lt;/span&gt;
&lt;span class="nb"&gt;object&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ref&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;object_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;object_version&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Datasets&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Manual&lt;/span&gt;
&lt;span class="n"&gt;dataset&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Dataset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;dataset_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;id&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;id1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;sentence&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;query1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;correction&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;gt1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;id&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;id2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;sentence&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;query2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;correction&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;gt2&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Calls&lt;/span&gt;
&lt;span class="n"&gt;dataset&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Dataset&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;from_calls&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;call_list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# DataFrame&lt;/span&gt;
&lt;span class="n"&gt;dataset&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Dataset&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;from_pandas&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Evaluations&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;evaluation&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Evaluation&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dataset&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;dataset&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scorers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;scorers_list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;evaluation&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;evaluate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Finalización&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Only needed on notebooks&lt;/span&gt;
&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;finish&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Pipeline de buenas prácticas&lt;/h2&gt;
&lt;h4&gt;1. Explorar los datos&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Inicializar una Run con &lt;code&gt;job_type='data_upload'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Crear un Artifact con &lt;code&gt;type='raw_data'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Añadir todos los archivos y carpetas al Artifact.&lt;/li&gt;
&lt;li&gt;Crear una tabla con los datos y añadirla al Artifact.&lt;/li&gt;
&lt;li&gt;Crear un Report con la tabla y anotar los hallazgos importantes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;2. Crear un dataset&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Inicializar una Run con &lt;code&gt;job_type='data_processing'&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;Descargar el Artifact del paso anterior (con los datos crudos).&lt;/li&gt;
&lt;li&gt;Procesar los datos según corresponda teniendo en cuenta los hallazgos del Report (split en train/valid/test, filtrado, etc).&lt;/li&gt;
&lt;li&gt;Crear un Artifact con &lt;code&gt;type='dataset'&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;Crear una nueva tabla de datos y añadirla al nuevo Artifact.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;3. Entrenar un modelo&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Integrar W&amp;amp;B con el framework de ML a utilizar.&lt;/li&gt;
&lt;li&gt;Almacenar todos los hiperparámetros en &lt;code&gt;wandb.config&lt;/code&gt; .&lt;/li&gt;
&lt;li&gt;Descargar el Artifact del paso anterior (con el dataset).&lt;/li&gt;
&lt;li&gt;Inicializar una Run con &lt;code&gt;job_type='model_training'&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;Entrenar un modelo.&lt;/li&gt;
&lt;li&gt;Crear un Artifact con &lt;code&gt;type='model'&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;Guardar las métricas finales en el diccionario &lt;code&gt;wandb.summary&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;Iterar focalizándose en la optimización de una única métrica. Establecer umbrales de mínimos y máximos para las demás métricas. &lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;4. Evaluar un modelo&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Inicializar una Run con &lt;code&gt;job_type='model_evaluation'&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;Descargar el Artifact del paso anterior (con el modelo).&lt;/li&gt;
&lt;li&gt;Chequear que las métricas de validación sean las mismas que antes.&lt;/li&gt;
&lt;li&gt;Crear y loggear tablas y gráficos según corresponda (tablas de predicciones, matrices de confusión, histogramas, etc). &lt;/li&gt;
&lt;li&gt;Crear un Report con los resultados y hacer análisis de errores.&lt;/li&gt;
&lt;li&gt;Una vez seleccionado un modelo para ser usado en producción, hacer inferencia en el test set y comprobar que las métricas sean creíbles y similares a las de validación. Si pasa la evaluación, promover el modelo al Model Registry. Caso contrario, significa que hay overfitting de validación o problemas de data leakage.&lt;/li&gt;
&lt;/ul&gt;</content><category term="MLOps"></category></entry><entry><title>Weights &amp; Biases platform</title><link href="https://facuroffet99.github.io/en/notes/mlops_1.html" rel="alternate"></link><published>2025-08-04T12:15:00-03:00</published><updated>2025-08-04T12:15:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-08-04:/en/notes/mlops_1.html</id><summary type="html">&lt;p&gt;Personal notes on the Weights &amp;amp; Biases platform: experiment tracking, Model Registry, W&amp;amp;B Weave for LLMs, and MLOps best practices pipeline.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Weights &amp; Biases platform&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;These are my personal notes from the courses &lt;a href="https://wandb.ai/site/courses/101/"&gt;Weights &amp;amp; Biases 101&lt;/a&gt;, &lt;a href="https://www.wandb.courses/courses/201-model-registry"&gt;Weights &amp;amp; Biases 201: Model Registry&lt;/a&gt;, &lt;a href="https://wandb.ai/site/courses/weave/"&gt;Weights &amp;amp; Biases 101: Weave&lt;/a&gt; and &lt;a href="https://wandb.ai/site/courses/effective-mlops/"&gt;Effective MLOps: Model development&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Training AI models: W\&amp;amp;B Models&lt;/h2&gt;
&lt;h4&gt;Runs&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;A Run is a unit of Python code execution that captures its entire context (library versions, hardware, system metrics, Git state, etc).&lt;/li&gt;
&lt;li&gt;It can include various types of logs: scalar metrics, media (images, histograms, 3D visualizations, videos, audio), plots, tables, and more.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Projects&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;A Project contains multiple Runs and all their associated data.&lt;/li&gt;
&lt;li&gt;In the GUI, a Project has different tabs:&lt;/li&gt;
&lt;li&gt;Overview: general information.&lt;/li&gt;
&lt;li&gt;Workspace: interactive dashboard with customizable panels to visualize results and compare Runs.&lt;/li&gt;
&lt;li&gt;Runs: table listing all the Runs in the Project.&lt;/li&gt;
&lt;li&gt;Automations: configured automated processes.&lt;/li&gt;
&lt;li&gt;Sweeps: a set of Runs that automatically explore different hyperparameters.&lt;/li&gt;
&lt;li&gt;Reports: flexible, auto-updating, interactive documents used to share visualizations from a Project.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Artifacts&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;An Artifact is a way to track and version any data used as input or output of a Run: datasets, evaluation results, or model checkpoints. It encapsulates both files and folders, and is composed of:&lt;/li&gt;
&lt;li&gt;A name&lt;/li&gt;
&lt;li&gt;A type (most useful types are 'dataset' and 'model')&lt;/li&gt;
&lt;li&gt;Metadata (as a dictionary)&lt;/li&gt;
&lt;li&gt;A description&lt;/li&gt;
&lt;li&gt;Files, folders, or references to external object storage (e.g., S3)&lt;/li&gt;
&lt;li&gt;Each time an Artifact with the same name is logged, it's compared to previous versions. If any difference is found, a new version is created with an alias (v1, v2, v3, etc).&lt;/li&gt;
&lt;li&gt;In the W\&amp;amp;B GUI you can view version info, metadata, contained files, lineage (a tree of processes that created or used the Artifact), and usage snippets.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Model Registry&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;The Model Registry is a centralized repository that hosts and organizes different Collections (also called Model Tasks).&lt;/li&gt;
&lt;li&gt;In other words, the Model Registry is where all models ready for public use live—either for testing or production.&lt;/li&gt;
&lt;li&gt;A Collection refers to a particular task (e.g., building segmentation, cell classification). It contains 'model'-type Artifacts that have been promoted as candidates for use by other teams or processes. Personal opinion: each Project should have a single associated Collection.&lt;/li&gt;
&lt;li&gt;A Collection can contain multiple versions of the same model, each with its own alias—for example: staging and production.&lt;/li&gt;
&lt;li&gt;Automations can be set up in the Model Registry—these are automatic actions triggered when a new model or alias is added (e.g., generating a Report).&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Developing applications with LLMs: W\&amp;amp;B Weave&lt;/h2&gt;
&lt;h4&gt;Calls&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Calls are the fundamental building block in Weave, representing a single function execution, including its inputs (arguments), outputs (returns), and metadata (timing, exceptions, etc).&lt;/li&gt;
&lt;li&gt;A Call can be related to another via parent/child relationships, forming a tree structure.&lt;/li&gt;
&lt;li&gt;Once created, a Call cannot be modified. You can only add feedback or delete it (both via code or GUI).&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Traces&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;A Trace (or Span) is a collection of Calls that share the same execution context.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Objects (Models and Datasets) and Ops&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;An Object is a data type that Weave can understand, serialize, and version. Models and Datasets are subclasses of Objects; Ops are functions/methods that operate on Objects.&lt;/li&gt;
&lt;li&gt;A Model allows you to version an app over time and understand how changes affect its responses. It consists of data (config, checkpoint, etc.) and code that defines how the model operates.&lt;/li&gt;
&lt;li&gt;To create a Model, define a class that inherits from &lt;code&gt;weave.Model&lt;/code&gt;, specify type annotations for all fields, and implement an &lt;code&gt;invoke&lt;/code&gt; or &lt;code&gt;predict&lt;/code&gt; method decorated with &lt;code&gt;@weave.op&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;When model-defining parameters change, the changes are logged and the model version is automatically updated.&lt;/li&gt;
&lt;li&gt;A Dataset is a collection of examples used to evaluate a Model.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Evaluations&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;An Evaluation assesses the performance of a Model on a Dataset using a specified list of metrics (functions or Scorers).&lt;/li&gt;
&lt;li&gt;Latency and token count are metrics logged by default.&lt;/li&gt;
&lt;li&gt;In the GUI, you can perform in-depth comparisons between different Evaluations.&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Basic usage in code&lt;/h2&gt;
&lt;h4&gt;Installation&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;pip install wandb weave
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Setup&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;wandb&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nn"&gt;weave&lt;/span&gt;
&lt;span class="n"&gt;wandb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;login&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nd"&gt;@weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;op&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;# decorator for every function/method to track (automatically included in common LLM libraries)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Initialization&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;run&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;wandb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;project&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;project_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entity&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;entity_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;job_type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;job_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;dict_with_configs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;init&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;project_name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# only needed when using weave as standalone&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Logging&lt;/h4&gt;
&lt;p&gt;Scalars and files:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;train/epoch&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;epoch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;train/train_loss&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;train_loss&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;val/val_loss&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;val_loss&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;val/accuracy&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;acc&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;log_model&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path_to_model_file&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# same as creating an Artifact of type &amp;#39;model&amp;#39;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Artifacts:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Log&lt;/span&gt;
&lt;span class="n"&gt;artifact&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;wandb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Artifact&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;artifact_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;artifact_type&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;artifact&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_file&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path_to_file&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;artifact&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_dir&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path_to_folder&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;log_artifact&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;artifact&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Retrieve&lt;/span&gt;
&lt;span class="n"&gt;artifact&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;use_artifact&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;artifact_name&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;:&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;artifact_version&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;artifact_dir&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;artifact&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;download&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Objects:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Log&lt;/span&gt;
&lt;span class="n"&gt;weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;publish&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;variable_to_log&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;log_name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Retrieve&lt;/span&gt;
&lt;span class="nb"&gt;object&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ref&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;object_name&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;:&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;object_version&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Datasets&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Manual&lt;/span&gt;
&lt;span class="n"&gt;dataset&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Dataset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;dataset_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;id&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;id1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;sentence&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;query1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;correction&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;gt1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;id&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;id2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;sentence&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;query2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;correction&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;gt2&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# From Calls&lt;/span&gt;
&lt;span class="n"&gt;dataset&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Dataset&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;from_calls&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;call_list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# From DataFrame&lt;/span&gt;
&lt;span class="n"&gt;dataset&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Dataset&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;from_pandas&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Evaluations&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;evaluation&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;weave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Evaluation&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dataset&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;dataset&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scorers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;scorers_list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;evaluation&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;evaluate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4&gt;Finalization&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Only needed in notebooks&lt;/span&gt;
&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;finish&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Aquí tenés la traducción al inglés de la nueva sección, adaptada al estilo del resto del documento:&lt;/p&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Best practices pipeline&lt;/h2&gt;
&lt;h4&gt;1. Explore the data&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Initialize a Run with &lt;code&gt;job_type='data_upload'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Create an Artifact with &lt;code&gt;type='raw_data'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Add all files and folders to the Artifact.&lt;/li&gt;
&lt;li&gt;Create a Table with the data and add it to the Artifact.&lt;/li&gt;
&lt;li&gt;Create a Report with the Table and annotate key findings.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;2. Create a dataset&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Initialize a Run with &lt;code&gt;job_type='data_processing'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Download the raw data Artifact from the previous step.&lt;/li&gt;
&lt;li&gt;Process the data as needed, based on the findings in the Report (e.g., train/valid/test split, filtering, etc.).&lt;/li&gt;
&lt;li&gt;Create an Artifact with &lt;code&gt;type='dataset'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Create a new data Table and add it to the new Artifact.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;3. Train a model&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Integrate W\&amp;amp;B with the ML framework being used.&lt;/li&gt;
&lt;li&gt;Store all hyperparameters in &lt;code&gt;wandb.config&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Download the dataset Artifact from the previous step.&lt;/li&gt;
&lt;li&gt;Initialize a Run with &lt;code&gt;job_type='model_training'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Train a model.&lt;/li&gt;
&lt;li&gt;Create an Artifact with &lt;code&gt;type='model'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Save final metrics to the &lt;code&gt;wandb.summary&lt;/code&gt; dictionary.&lt;/li&gt;
&lt;li&gt;Iterate with a focus on optimizing a single key metric. Set minimum/maximum thresholds for the remaining metrics.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;4. Evaluate a model&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Initialize a Run with &lt;code&gt;job_type='model_evaluation'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Download the model Artifact from the previous step.&lt;/li&gt;
&lt;li&gt;Ensure validation metrics are consistent with previous runs.&lt;/li&gt;
&lt;li&gt;Create and log appropriate tables and visualizations (prediction tables, confusion matrices, histograms, etc.).&lt;/li&gt;
&lt;li&gt;Create a Report with the results and perform error analysis.&lt;/li&gt;
&lt;li&gt;Once a model is selected for production, run inference on the test set and verify that metrics are realistic and similar to validation. If it passes evaluation, promote the model to the Model Registry. If not, it likely indicates validation overfitting or data leakage issues.&lt;/li&gt;
&lt;/ul&gt;</content><category term="MLOps"></category></entry><entry><title>Teoría de juegos</title><link href="https://facuroffet99.github.io/notes/decision_making_1.html" rel="alternate"></link><published>2025-07-19T20:10:00-03:00</published><updated>2025-07-19T20:10:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-07-19:/notes/decision_making_1.html</id><summary type="html">&lt;p&gt;Notas personales sobre teoría de juegos: dominancia de estrategias, equilibrio de Nash, juegos de coordinación, estrategias mixtas, evolución, juegos secuenciales e interacciones repetidas. Basadas en el curso de Ben Polak (Yale) y Veritasium.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Teoría de juegos&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;Estas son mis notas personales del curso &lt;a href="https://www.youtube.com/playlist?list=PL6EF60E1027E1A10B"&gt;Game Theory with Ben Polak&lt;/a&gt; de Yale, y del video &lt;a href="https://www.youtube.com/watch?v=mScpHTIi-kM&amp;amp;pp=ygUWdmVyaXRhc2l1bSBnYW1lIHRoZW9yeQ%3D%3D"&gt;What Game Theory Reveals About Conflict and War&lt;/a&gt; de Veritasium. &lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Definiciones iniciales&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Un juego está compuesto necesariamente por jugadores, sets de estrategias y recompensas. Por ejemplo, los jugadores pueden ser 1 y 2, los sets de estrategias ser S₁={T,B} y S₂={L,C,R} y las recompensas ser u₁(T,C)=11 y u₂(T,C)=3.&lt;/li&gt;
&lt;li&gt;En una instancia particular de un juego, cada jugador elige una estrategia de su set y se determina un perfil de estrategias "s" para ese juego. Por ejemplo, s₁=T y s₂=C conforman el vector s=(T,C).&lt;/li&gt;
&lt;li&gt;Una estrategia sᵢ' domina estrictamente a otra estrategia propia sᵢ si la recompensa para sᵢ' es estrictamente mayor que la de sᵢ sin importar lo que hagan los demás jugadores: uᵢ(sᵢ', s₋ᵢ) &amp;gt; uᵢ(sᵢ, s₋ᵢ) para todo s₋ᵢ.&lt;/li&gt;
&lt;li&gt;En el caso de que la recompensa de sᵢ' sea mayor o igual a la de sᵢ (para cualquier estrategia de los demás jugadores), entonces sᵢ' domina débilmente a sᵢ: uᵢ(sᵢ', s₋ᵢ) ≥ uᵢ(sᵢ, s₋ᵢ) para todo s₋ᵢ.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Lecciones del dilema del prisionero&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Cooperar es una estrategia estrictamente dominada: los jugadores racionales no van a elegirla.&lt;/li&gt;
&lt;li&gt;La elección racional puede derivar en resultados malos para todos los jugadores: la racionalidad individual no siempre conduce al bien colectivo.&lt;/li&gt;
&lt;li&gt;Cambiar las recompensas puede alterar considerablemente al juego: no se puede obtener lo que uno quiere hasta no saber qué es lo que uno quiere.&lt;/li&gt;
&lt;li&gt;Si los demás jugadores poseen estrategias estrictamente dominantes, hay que jugar en consecuencia de ellas: ponerse en los zapatos de los demás para determinar qué es lo que van a hacer.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Eliminación iterativa de estrategias dominadas&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Como ningún jugador racional elegirá una estrategia estrictamente dominada, las mismas pueden ser eliminadas. De esta forma, se forma un "juego reducido" en el que nuevamente se puede repetir el proceso hasta que no puedan eliminarse más estrategias. &lt;/li&gt;
&lt;li&gt;Esto solo aplica en el caso de que exista conocimiento común de racionalidad: vos creés que los demás jugadores van a actuar en forma racional, ellos creen que vos vas actuar en forma racional, vos creés que ellos creen que vas a actuar en forma racional, etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Mejores respuestas&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Una estrategia sᵢ' es una mejor respuesta ante la estrategia s₋ᵢ de los demás jugadores si la recompensa de elegir sᵢ' es mayor o igual que elegir cualquier otra estrategia: uᵢ(sᵢ',s₋ᵢ) ≥ uᵢ(sᵢ,s₋ᵢ) para todo sᵢ. Por lo tanto, sᵢ' maximiza uᵢ(sᵢ,s₋ᵢ) con respecto a sᵢ.&lt;/li&gt;
&lt;li&gt;Si un juego no se puede resolver eliminando estrategias dominadas (porque no hay o porque el set de estrategias es continuo), entonces hay que tener en cuenta las creencias propias (en porcentaje) de lo que los demás jugadores van a hacer.&lt;/li&gt;
&lt;li&gt;Una estrategia sᵢ' es una mejor respuesta ante la creencia p sobre las decisiones de los demás jugadores si la esperanza de recompensa al elegir sᵢ' es mayor o igual que la esperanza de elegir cualquier otra estrategia: E[uᵢ(sᵢ',p)] ≥ E[uᵢ(sᵢ,p)] para todo sᵢ. Por lo tanto, sᵢ' maximiza E[uᵢ(sᵢ,p)] con respecto a sᵢ.&lt;/li&gt;
&lt;li&gt;Una estrategia es racionalizable si es compatible con al menos una de las posibles creencias sobre los demás jugadores. Esto significa que no hay que elegir estrategias que no sean mejores respuestas ante ninguno de los casos posibles.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Equilibrio de Nash (NE)&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Un perfil de estrategias s' es NE si la estrategia elegida por cada jugador (sᵢ') es una mejor respuesta ante las estrategias elegidas por cada otro jugador (s₋ᵢ').&lt;/li&gt;
&lt;li&gt;Un NE implica que no hay arrepentimiento en los jugadores: manteniendo las estrategias ajenas fijas, nadie tiene incentivos estrictos para desviarse de su estrategia. También se puede decir que es una profecía autocumplida: creer que los demás van a jugar un NE hace que uno también lo haga.&lt;/li&gt;
&lt;li&gt;Teorema de Existencia de Nash: todo juego finito (en jugadores y estrategias) tiene al menos un NE si se permiten estrategias mixtas. &lt;/li&gt;
&lt;li&gt;Una estrategia estrictamente dominada jamás puede ser jugada en un NE.&lt;/li&gt;
&lt;li&gt;Un juego tiende a converger a un NE (en caso de que exista) tras ser repetido varias veces.&lt;/li&gt;
&lt;li&gt;Sí un jugador se desvía de un NE pero los demás jugadores prefieren mantener sus estrategias, entonces el NE es robusto ante pequeñas variaciones. En cambio, si a los demás jugadores también les conviene cambiar desviarse, entonces el NE no es robusto a ellas.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Juegos de coordinación&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Los juegos de coordinación poseen más de un NE. Hay casos donde hay NEs mejores que otros para todos los jugadores, otros donde todos los NEs son iguales, y otros donde cada jugador prefiere un NE distinto.&lt;/li&gt;
&lt;li&gt;Dependiendo de las creencias de los jugadores, es posible que se llegue a un NE "malo". Pero si los jugadores se comunican y coordinan, pueden moverse hacia un NE "bueno" y así salir ganando todos.&lt;/li&gt;
&lt;li&gt;Es un caso distinto al dilema del prisionero porque la comunicación puede hacer que se pase de un NE a otro, pero no puede hacer que se elija una estrategia estrictamente dominada.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Estrategias mixtas&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Una estrategia mixta pᵢ es una elección aleatoria entre las posibles estrategias puras sᵢ. Esto puede convenir cuando no existe un NE usando solo estrategias puras o cuando los jugadores prefieren distintos NE. Por ejemplo, pᵢ = (1/2, 1/2, 0) &lt;/li&gt;
&lt;li&gt;Una estrategia pura es un caso especial de una estrategia mixta, en donde una única estrategia tiene una probabilidad de 1 y el resto de 0.&lt;/li&gt;
&lt;li&gt;Cuando se juega una estrategia mixta, la recompensa esperada es un promedio ponderado de las recompensas esperadas de cada una de las estrategias puras. Esto significa que la recompensa esperada siempre se encuentra en algún punto entre la mayor y la menor recompensa posible.&lt;/li&gt;
&lt;li&gt;La condición para que un perfil de estrategias mixtas p' sea un NE es la misma que antes: cada pᵢ' es mejor respuesta con respecto a p₋ᵢ'. &lt;/li&gt;
&lt;li&gt;Si una estrategia mixta es una mejor respuesta, entonces cada una de las estrategias involucradas (con probabilidad mayor a cero) también tienen que ser mejores respuestas. &lt;/li&gt;
&lt;li&gt;Combinando los dos puntos anteriores se deriva que, para que un mix sea NE, las recompensas esperadas para cada una de las estrategias de un jugador tienen que ser iguales (si no lo fueran se descartarían las estrategias que llevan a menores recompensas). Estas recompensas dependen de las probabilidades de los demás, no de las propias.&lt;/li&gt;
&lt;li&gt;Hay tres posibles interpretaciones acerca de las probabilidades en una estrategia mixta: aleatorización (depende del azar), creencias (depende de lo que uno cree que los demás van a hacer) y proporciones (depende de las diferencias entre subgrupos de una población).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Evolución&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;En un contexto biológico, se pueden asociar a las estrategias con genes y a las recompensas con aptitud genética. Dichas estrategias no son elegidas por individuos racionales sino que están "cableadas" biológicamente.&lt;/li&gt;
&lt;li&gt;Una estrategia crece si le va bien (la población con el gen continúa reproduciéndose) o muere si le va mal (la población con el gen se extingue). Lo que importa es la supervivencia del gen, no la del individuo.&lt;/li&gt;
&lt;li&gt;En un juego simétrico de dos jugadores, una estrategia s' (ya sea pura o mixta) es evolutivamente estable (ES) si se cumplen dos condiciones:&lt;ul&gt;
&lt;li&gt;1: El perfil (s', s') es un NE (u(s',s') ≥ u(s,s') para todo s).&lt;/li&gt;
&lt;li&gt;2: Si u(s',s') = u(s,s') para algún s, entonces se tiene que dar que u(s',s) &amp;gt; u(s,s) (la estrategia original debe ser mejor contra la invasora que la invasora contra sí misma).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;En el dilema del prisionero, cooperar no es una estrategia ES pero desertar sí lo es.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Juegos secuenciales&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Que un juego sea simultáneo o secuencial no depende del flujo del tiempo, sino del flujo de información.&lt;/li&gt;
&lt;li&gt;Backward induction es el proceso de determinar la secuencia optima de acciones (en cada punto de un árbol) al razonar desde el punto final de un juego. Funciona eliminando las amenazas que no son creíbles.  &lt;/li&gt;
&lt;li&gt;En algunos casos, tener más información, más opciones o mayores recompensas en juegos secuenciales puede ser contraproducente. Por ejemplo, que un rival sepa que uno tiene cierta información puede llevarlo a realizar acciones que te impacten negativamente.&lt;/li&gt;
&lt;li&gt;Un juego es de información perfecta si, para cada nodo, el jugador que le toca su turno sabe en que nodo se encuentra. En este tipo de juego, una estrategia es un plan de acción completo que especifica qué acción se debe elegir en cada nodo.&lt;/li&gt;
&lt;li&gt;Teorema de Zermelo: cualquier juego de dos jugadores con información perfecta, nodos finitos y tres posibles resultados (victoria, derrota o empate) puede ser resuelto. Esto quiere decir que, suponiendo que ambos jugadores juegan a la perfección, siempre alguno puede forzar una victoria o un empate.&lt;/li&gt;
&lt;li&gt;La paradoja de la cadena de tiendas enseña que a veces conviene tomar acciones que parecen no racionales para establecer una reputación que te ayude a largo plazo.&lt;/li&gt;
&lt;li&gt;Juego de negociación con ofertas alternadas: si se asume que una negociación puede ser eterna, que las ofertas se pueden hacer muy rápido (el factor de descuento es cercano a uno) y que ambos jugadores tienen el mismo factor de descuento (son igual de impacientes; sopesan el futuro y el presente de la misma manera), entonces la repartición de la diferencia va a tender a ser repartida mitad y mitad directamente en la primera oferta. En un caso más realista, esto último no se cumple porque uno no puede saber exactamente cuál es el factor de descuento de los demás ni cuál es el valor que asignan al objeto por el que se negocia.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Juegos de información imperfecta&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Que en un juego haya información imperfecta significa que hay casos donde un jugador no sabe en qué nodo del árbol del juego se encuentra. Estos nodos indistinguibles forman un set de información, y en ellos no se puede aplicar backward induction.&lt;/li&gt;
&lt;li&gt;Un juego simultáneo puede pensarse como un juego secuencial con información imperfecta: jugar a la vez es lo mismo que no saber lo que el rival jugó; lo importante no es el tiempo sino la información.&lt;/li&gt;
&lt;li&gt;Un subjuego cumple tres condiciones: empieza en un único nodo, contiene todos los nodos sucesores del inicial, y no rompe ningún set de información.&lt;/li&gt;
&lt;li&gt;Un NE es perfecto en subjuegos (SPNE) si induce un NE en cada subjuego existente.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Interacciones repetidas&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;En una relación que se mantiene a lo largo del tiempo, la promesa de recompensas futuras y/o la amenaza de futuros castigos a veces puede incentivar a la cooperación. Pero para que esto funcione, justamente tiene que haber un futuro: la relación no puede tener un final premeditado.&lt;/li&gt;
&lt;li&gt;Mientras más peso tenga el futuro (que puede estar relacionado con la importancia, paciencia o probabilidad de que exista), es más fácil que los incentivos para cooperar superen a las tentaciones de desertar.&lt;/li&gt;
&lt;li&gt;En un juego repetido indefinidamente, casi cualquier resultado que sea mejor para todos los jugadores que el peor castigo posible puede ser sostenido como un NE, siempre y cuando los jugadores sean lo suficientemente pacientes. &lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Torneos de Axelrod&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;La cooperación puede emerger y sostenerse aún cuando los jugadores solo están motivados por su interés propio; el altruismo no es necesario. &lt;/li&gt;
&lt;li&gt;Tit for Tat y las demás estrategias con buenos desempeños poseen cuatro características:&lt;ul&gt;
&lt;li&gt;1: Bondad: cooperan por defecto.&lt;/li&gt;
&lt;li&gt;2: Perdón: no dejan que las rondas anteriores a la última influencien las decisiones actuales.&lt;/li&gt;
&lt;li&gt;3: Provocabilidad: no se dejan pasar por encima, toman represalias inmediatamente.&lt;/li&gt;
&lt;li&gt;4: Claridad: es posible entenderlas y  establecer un patrón de confianza con ellas.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;No existe una estrategia óptima, siempre la mejor elección depende de las estrategias con las que se vaya a interactuar.&lt;/li&gt;
&lt;li&gt;Como un ambiente realista es ruidoso (existe una pequeña probabilidad de que una cooperación sea percibida como una deserción y visceversa), TFT tiene la limitación de permitir bucles infinitos de represalias. &lt;/li&gt;
&lt;li&gt;Algunas características que incorporan estrategias más complejas son: tolerancia (aceptar que los errores existen y perdonarlos), memoria (recordar estados previos al último), adaptación (cambiar de comportamiento de acuerdo al oponente) y contextualidad (formar alianzas y castigar a oportunistas).&lt;/li&gt;
&lt;/ul&gt;</content><category term="Toma de decisiones"></category></entry><entry><title>Game theory</title><link href="https://facuroffet99.github.io/en/notes/decision_making_1.html" rel="alternate"></link><published>2025-07-19T20:10:00-03:00</published><updated>2025-07-19T20:10:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-07-19:/en/notes/decision_making_1.html</id><summary type="html">&lt;p&gt;Personal notes on game theory: strategy dominance, Nash equilibrium, coordination games, mixed strategies, evolution, sequential games, and repeated interactions. Based on Ben Polak's Yale course and Veritasium.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Game theory&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;These are my personal notes from the course &lt;a href="https://www.youtube.com/playlist?list=PL6EF60E1027E1A10B"&gt;Game Theory with Ben Polak&lt;/a&gt; by Yale, and from the video &lt;a href="https://www.youtube.com/watch?v=mScpHTIi-kM&amp;amp;pp=ygUWdmVyaXRhc2l1bSBnYW1lIHRoZW9yeQ%3D%3D"&gt;What Game Theory Reveals About Conflict and War&lt;/a&gt; by Veritasium.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Initial definitions&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;A game is necessarily composed of players, strategy sets, and payoffs. For example, the players may be 1 and 2, the strategy sets S₁={T,B} and S₂={L,C,R}, and the payoffs u₁(T,C)=11 and u₂(T,C)=3.&lt;/li&gt;
&lt;li&gt;In a specific instance of a game, each player chooses a strategy from their set, forming a strategy profile "s" for that game. For instance, s₁=T and s₂=C give the profile s=(T,C).&lt;/li&gt;
&lt;li&gt;A strategy sᵢ' strictly dominates another strategy sᵢ of the same player if its payoff is strictly greater regardless of what the other players do: uᵢ(sᵢ', s₋ᵢ) &amp;gt; uᵢ(sᵢ, s₋ᵢ) for all s₋ᵢ.&lt;/li&gt;
&lt;li&gt;If the payoff of sᵢ' is greater than or equal to that of sᵢ (for any strategy of the other players), then sᵢ' weakly dominates sᵢ: uᵢ(sᵢ', s₋ᵢ) ≥ uᵢ(sᵢ, s₋ᵢ) for all s₋ᵢ.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Lessons from the prisoner's dilemma&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Cooperating is a strictly dominated strategy: rational players will not choose it.&lt;/li&gt;
&lt;li&gt;Rational choices can lead to bad outcomes for all players: individual rationality does not always lead to collective good.&lt;/li&gt;
&lt;li&gt;Changing the payoffs can drastically alter the game: you can’t know what to aim for until you know what you want.&lt;/li&gt;
&lt;li&gt;If other players have strictly dominant strategies, you must act accordingly: put yourself in their shoes to predict what they will do.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Iterated elimination of dominated strategies&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Since no rational player would choose a strictly dominated strategy, such strategies can be eliminated. This creates a "reduced game" where the process can be repeated until no more eliminations are possible.&lt;/li&gt;
&lt;li&gt;This only applies when there is common knowledge of rationality: you believe others are rational, they believe you are rational, you believe they believe you are rational, etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Best responses&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;A strategy sᵢ' is a best response to the strategy s₋ᵢ of the other players if its payoff is greater than or equal to any other strategy: uᵢ(sᵢ',s₋ᵢ) ≥ uᵢ(sᵢ,s₋ᵢ) for all sᵢ. So, sᵢ' maximizes uᵢ(sᵢ,s₋ᵢ) with respect to sᵢ.&lt;/li&gt;
&lt;li&gt;If a game can't be solved by eliminating dominated strategies (because there are none or the strategy set is continuous), then beliefs (in percentages) about what the others will do must be considered.&lt;/li&gt;
&lt;li&gt;A strategy sᵢ' is a best response to belief p about others’ choices if the expected payoff of choosing sᵢ' is greater than or equal to that of any other strategy: E[uᵢ(sᵢ',p)] ≥ E[uᵢ(sᵢ,p)] for all sᵢ. So, sᵢ' maximizes E[uᵢ(sᵢ,p)] with respect to sᵢ.&lt;/li&gt;
&lt;li&gt;A strategy is rationalizable if it is a best response to at least one possible belief about the other players. This means you should not pick strategies that are not best responses to any possible scenario.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Nash equilibrium (NE)&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;A strategy profile s' is a NE if each player's strategy (sᵢ') is a best response to the strategies chosen by the others (s₋ᵢ').&lt;/li&gt;
&lt;li&gt;In a NE, players have no regrets: holding others’ strategies fixed, no one has a strict incentive to deviate. It’s also a self-fulfilling prophecy: believing others will play a NE leads you to play it too.&lt;/li&gt;
&lt;li&gt;Nash Existence Theorem: every finite game (in players and strategies) has at least one NE if mixed strategies are allowed.&lt;/li&gt;
&lt;li&gt;A strictly dominated strategy can never be played in a NE.&lt;/li&gt;
&lt;li&gt;A game tends to converge to a NE (if it exists) after being repeated several times.&lt;/li&gt;
&lt;li&gt;If a player deviates from a NE but others prefer to keep their strategies unchanged, then the NE is robust to small variations. If others also prefer to deviate, the NE is not robust.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Coordination games&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Coordination games have more than one NE. Some cases have NE that are better for all players, others have identical NE, and others have players preferring different NE.&lt;/li&gt;
&lt;li&gt;Depending on players’ beliefs, a “bad” NE may be reached. But communication and coordination can lead to a “better” NE where all players benefit.&lt;/li&gt;
&lt;li&gt;This differs from the prisoner’s dilemma, where communication cannot lead to a strictly dominated strategy being chosen.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Mixed strategies&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;A mixed strategy pᵢ is a random choice among the pure strategies sᵢ. This may be useful when no pure strategy NE exists or when players prefer different NE. For example, pᵢ = (1/2, 1/2, 0).&lt;/li&gt;
&lt;li&gt;A pure strategy is a special case of a mixed strategy where one strategy has probability 1 and the rest have 0.&lt;/li&gt;
&lt;li&gt;When using a mixed strategy, the expected payoff is a weighted average of the payoffs from each pure strategy. Thus, it always lies between the highest and lowest possible payoff.&lt;/li&gt;
&lt;li&gt;For a profile of mixed strategies p' to be a NE, each pᵢ' must be a best response to p₋ᵢ'.&lt;/li&gt;
&lt;li&gt;If a mixed strategy is a best response, then each strategy involved (with nonzero probability) must also be a best response.&lt;/li&gt;
&lt;li&gt;Combining the above: for a mix to be a NE, the expected payoffs of all strategies in the mix must be equal (otherwise, lower-payoff strategies would be dropped). These expected payoffs depend on the others’ probabilities, not one’s own.&lt;/li&gt;
&lt;li&gt;There are three possible interpretations of probabilities in mixed strategies: randomization (truly random behavior), beliefs (what one thinks others will do), and proportions (subgroup differences in a population).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Evolution&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;In a biological context, strategies can be linked to genes and payoffs to genetic fitness. These strategies are not chosen rationally but are “hardwired” biologically.&lt;/li&gt;
&lt;li&gt;A strategy spreads if it performs well (i.e., the population with the gene reproduces) or dies out if it performs poorly (gene extinction). What matters is gene survival, not the individual.&lt;/li&gt;
&lt;li&gt;In a symmetric two-player game, a strategy s' (pure or mixed) is evolutionarily stable (ES) if:&lt;ul&gt;
&lt;li&gt;1: (s', s') is a NE (u(s',s') ≥ u(s,s') for all s).&lt;/li&gt;
&lt;li&gt;2: If u(s',s') = u(s,s') for some s, then u(s',s) &amp;gt; u(s,s) (the original strategy must beat the invader when facing it).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;In the prisoner’s dilemma, cooperation is not ES but defection is.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Sequential games&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Whether a game is simultaneous or sequential depends on information flow, not time flow.&lt;/li&gt;
&lt;li&gt;Backward induction is the process of finding the optimal action sequence (at each tree point) by reasoning backwards from the game’s end. It eliminates non-credible threats.&lt;/li&gt;
&lt;li&gt;In some cases, having more information, more options, or higher payoffs in sequential games can backfire. For example, if a rival knows you have certain information, they might act in ways that hurt you.&lt;/li&gt;
&lt;li&gt;A game has perfect information if, at every node, the player whose turn it is knows exactly where they are. In such games, a strategy is a full plan specifying what to do at every node.&lt;/li&gt;
&lt;li&gt;Zermelo’s Theorem: any two-player game with perfect information, finite nodes, and three possible outcomes (win, lose, draw) is solvable. Assuming perfect play, one player can force a win or draw.&lt;/li&gt;
&lt;li&gt;The chain store paradox teaches that it can be beneficial to take seemingly irrational actions to build a long-term reputation.&lt;/li&gt;
&lt;li&gt;Alternating-offer bargaining game: if the negotiation can go on indefinitely, offers can be made quickly (discount factor close to 1), and players have the same discount factor (equally impatient), then the surplus is split 50/50 in the first offer. Realistically, this rarely holds, as players can’t know each other’s discount factors or valuations perfectly.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Games with imperfect information&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;A game has imperfect information when a player doesn’t know which node they are at. These indistinguishable nodes form an information set, and backward induction doesn’t apply in them.&lt;/li&gt;
&lt;li&gt;A simultaneous game can be viewed as a sequential game with imperfect information: playing at the same time is equivalent to not knowing what the opponent played. What matters is information, not timing.&lt;/li&gt;
&lt;li&gt;A subgame meets three conditions: it starts at a single node, contains all successor nodes, and doesn’t break any information sets.&lt;/li&gt;
&lt;li&gt;A NE is subgame perfect (SPNE) if it induces a NE in every subgame.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Repeated interactions&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;In ongoing relationships, the promise of future rewards and/or threat of future punishments can incentivize cooperation. But for this to work, there must be a future: the relationship must not have a known endpoint.&lt;/li&gt;
&lt;li&gt;The more weight the future carries (which may depend on importance, patience, or the probability that a future exists), the easier it is for incentives to cooperate to outweigh the temptations to defect.&lt;/li&gt;
&lt;li&gt;In an indefinitely repeated game, almost any outcome that is better for all players than the worst possible punishment can be sustained as a NE, provided players are patient enough.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Axelrod tournaments&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Cooperation can emerge and be sustained even when players are purely self-interested; altruism is not required.&lt;/li&gt;
&lt;li&gt;Tit for Tat and other well-performing strategies share four characteristics:&lt;ul&gt;
&lt;li&gt;1: Niceness: they cooperate by default.&lt;/li&gt;
&lt;li&gt;2: Forgiveness: they don’t let past rounds (beyond the last) influence current decisions.&lt;/li&gt;
&lt;li&gt;3: Provocability: they retaliate immediately when wronged.&lt;/li&gt;
&lt;li&gt;4: Clarity: they are understandable and help establish a pattern of trust.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;There is no optimal strategy—what works best depends on who you're interacting with.&lt;/li&gt;
&lt;li&gt;Since real environments are noisy (a cooperation may be mistaken for defection and vice versa), TFT’s weakness is the possibility of infinite retaliation loops.&lt;/li&gt;
&lt;li&gt;More complex strategies may include features like: tolerance (accepting and forgiving mistakes), memory (remembering more than the last state), adaptation (adjusting to the opponent’s behavior), and contextuality (forming alliances and punishing opportunists).&lt;/li&gt;
&lt;/ul&gt;</content><category term="Decision making"></category></entry><entry><title>Filosofía no occidental</title><link href="https://facuroffet99.github.io/notes/philosophy_3.html" rel="alternate"></link><published>2025-06-19T15:08:00-03:00</published><updated>2025-06-19T15:08:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-06-19:/notes/philosophy_3.html</id><summary type="html">&lt;p&gt;Notas personales sobre filosofía no occidental: escuelas indias (budismo, jainismo, Samkhya), filosofía china (Confucio, Laozi, Zhuangzi) y filosofía árabe-persa (Avicena, Averroes, Al-Ghazali). Basadas en A.C. Grayling y el podcast Philosophize This!&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Filosofía no occidental&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;Estas son mis notas personales de la Parte 5 del libro &lt;a href="https://www.google.com.ar/books/edition/The_History_of_Philosophy/tkvRvQEACAAJ?hl=es-419"&gt;Historia de la Filosofía&lt;/a&gt; de A.C. Grayling, y de los episodios 7 a 9, 18 y 19 del podcast &lt;a href="https://open.spotify.com/show/2Shpxw7dPoxRJCdfFXTWLE"&gt;Philosophize This!&lt;/a&gt; de Stephen West. De ninguna forma esto pretende ser un análisis exhaustivo de la filosofía de las ricas culturas de oriente, sino un mero repaso de sus figuras más influyentes.&lt;/p&gt;
&lt;p&gt;Introduzco a cada filósofo con el formato &lt;em&gt;Nombre (Año, Lugar - Descripción)&lt;/em&gt;. Año se corresponde con el año de nacimiento (o su aproximado, hay fechas que no se saben con seguridad), y Lugar con el país actual de su ciudad de nacimiento. En Descripción subrayo bien lo que yo considero es el aporte principal del filósofo o bien un suceso que me haga recordarlo fácilmente.&lt;/p&gt;
&lt;p&gt;En el caso de la filosofía india, es más conveniente agrupar a los pensamientos filosóficos en escuelas en lugar de hablar de filósofos individuales.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;El sufrimiento es rápido pero nosotros más - Filosofía india&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Escuela Samkhya&lt;/strong&gt; (conciencia libre): Existe un dualismo entre purusha (conciencia pura) y prakriti (todo lo que no es conciencia). El prakriti es estable cuando sus tres propiedades están equilibradas, que son algo así como iluminación, oscuridad y movimiento. La purusha es ontológicamente superior al prakriti, y la liberación consiste en darnos cuenta de ello: no estamos atados al prakriti porque la purusha siempre ha sido libre.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Escuela Yoga&lt;/strong&gt; (meditación): Se adhiere a la metafísica Samkhya y añade componentes prácticos: la conciencia es el existente primario, y su nivel más profundo de liberación se puede desatar por medio de técnicas de postura, respiración y meditación.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Escuela Nyaya-Vaishésika&lt;/strong&gt; (lógica para categorizar las cosas): Existir es tener las capacidades de conocer y de nombrar, por medio de la percepción sensorial, la inferencia, la comparación y el testimonio de expertos. Todo está compuesto por átomos indivisibles, eternos y totalmente distintos entre sí, que se unen y dan forma a las sustancias impermanentes. Lo que mantiene unida a una sustancia (una hoja) con una cualidad (su color) es tan real como ellas: la inherencia es algo que se encuentra entre la parte y el todo. El efecto no está contenido en una causa, sino que es creado de cero por esta.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Escuela Purva Mimamsa / Karma Mimamsa&lt;/strong&gt; (ritualismo): Las escrituras son la única fuente confiable de conocimiento, su autoridad es total y se necesita una fe incuestionable en ellas. Si no se realizan los rituales y sacrificios exigidos, el universo sufre efectos perversos.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Escuela Vedanta / Uttara Mimamsa&lt;/strong&gt; (relación ser-existencia): El camino hacia la liberación se encuentra en conocer cuál es la relación entre el ser individual (atman) y la realidad definitiva (Brahman). Existen distintas subescuelas que poseen diferentes interpretaciones: pueden ser idénticos, uno parte del otro, o distintos.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Escuela Chárvaka / Lokáyata&lt;/strong&gt; (empirismo radical) - La percepción sensorial es la única fuente válida de conocimiento, y ella no nos dice nada sobre la existencia de la reencarnación ni de la utilidad de los rituales y sacrificios. Entonces, no hay razón para creer en ellos. Lo único real es el mundo material, por lo que la búsqueda del placer y el rechazo al dolor son buenos.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Budismo&lt;/strong&gt; (supresión del ego): El futuro no está controlado por dioses sobrenaturales, el destino depende completamente de uno mismo. No se debe buscar la liberación del alma porque el alma no existe; el "yo" es una ilusión. Existen cuatro verdades nobles: &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1: El sufrimiento es universal, y la disatisfacción es el estado por defecto de la mente humana (la satisfacción existe pero eventualmente se desvanece). &lt;/li&gt;
&lt;li&gt;2: La disatisfacción es causada por el deseo y las expectativas, que a su vez son causados por el egoísmo y por la ilusión de que vivimos separados de todo el resto del universo. &lt;/li&gt;
&lt;li&gt;3: El sufrimiento puede ser terminado al eliminar el deseo, y para eso hay que eliminar el ego (alcanzar el Nirvana). &lt;/li&gt;
&lt;li&gt;4: El camino a seguir para alcanzar el Nirvana para así acabar con el ciclo de sufrimiento y renacimientos (samsara) es el de la moralidad (palabras, acciones y estilo de vida), la meditación (esfuerzo, conciencia y concentración) y la sabiduría (entendimiento y resolución).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Jainismo&lt;/strong&gt; (perspectivismo): La liberación del sufrimiento se logra al superar el ciclo de renacimientos. El camino para la liberación consiste en la no violencia, el desapego, el ascetismo y la aceptación de que la realidad es multifacética e infinitamente compleja. Debido a esto, no existe una descripción única y absoluta para algo, sino múltiples puntos de vista que son verdaderos solo parcialmente. &lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Dejemos que todo fluya, pero por favor mantengamos el orden - Filosofía china&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Laozi&lt;/strong&gt; (571 aC, China - daoísmo): Existe un camino que lleva a desatar el potencial vital propio, y ese camino es el Dao. El lenguaje es inadecuado para describir al Dao: "el Dao que puede ser expresado con palabras no es el Dao eterno". El Dao trasciende todo lo que puede ser comprendido: es todo, es el origen de las cosas, es la fuente de la existencia, es el vacío que rodea las cosas, es nada. El camino del Dao debe ser seguido mediante el principio natural de wuwei: sin esfuerzo, dejando que las cosas sigan su curso, sin interferir. "El sabio actúa sin esfuerzo, enseña sin muchas palabras, produce sin poseer, crea pero es indiferente a su resultado, no reclama nada, y por ello mismo no tiene nada que perder".&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Confucio&lt;/strong&gt; (551 aC, China - respeto a las tradiciones): El mejor gobernante es el que gobierna a través del buen ejemplo, como si se tratase de una relación padre-hijo. Una vida disciplinada y de benevolencia se logra al seguir de manera correcta y respetuosa los rituales establecidos históricamente por las figuras de autoridad. Para ser benevolente, primero hay que poder distinguir a la gente buena de la mala: "no hagas a los demás lo que no quieras que te hagan". Lo más importante es estar continuamente intentado mejorar para ser la mejor persona posible, evitando así tomar una actitud complaciente y de inacción. &lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Mozi&lt;/strong&gt; (468 aC, China - utilitarismo del amor): Hay que amar y valorar a los demás como se lo hace a uno mismo para proteger la armonía, seguridad y paz de la sociedad. Continuamente hay que sopesar los beneficios y los perjuicios de las cosas para evitar confundir lo habitual con lo correcto y la costumbre con lo acertado.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Zhuangzi&lt;/strong&gt; (369 aC, China - el camino antes que él destino): Los humanos estamos mejor cuando nuestras vidas son simples y más cercanas al estado natural. Vivimos en una cantidad limitada de tiempo y el conocimiento a adquirir en el mundo es ilimitado, por lo que es inutil perseguirlo. Cuando se persigue el conocimiento, el objetivo es cada día añadir algo a tu vida; cuando se persigue al Dao, el objetivo es cada día remover algo de tu vida. Pero más importante que seguir el camino del Dao es el viaje interior y la experiencia personal de estar en él: lo ideal es vagabundear por el camino.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Xun Zi&lt;/strong&gt; (313 aC, China - el estandarizador): Los humanos somos seres codiciosos por naturaleza que buscamos nuestro beneficio personal, de forma que somos propensos al mal y ser buenos nos exige un esfuerzo conciente. La bondad es un producto artificial y un logro cultural, por lo que la educación y los modelos de conducta son necesarios para el desarrollo de una persona virtuosa. Como los nombres de las cosas son convenciones que varían según su aplicación, los gobernantes deben establecer los significados de los nombres por decreto para constituir un estándar que permita obedecer las leyes correctamente. Los rituales también deben ser estandarizados para promover el orden y la disciplina en la sociedad.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Han Fei&lt;/strong&gt; (280 aC, China - legalismo): La prioridad de un gobernante no tiene que ser el bienestar del pueblo, sino mantener el poder y el orden mediante leyes que imponen castigos. El gobernante debería parecer no hacer nada, oculto detrás del muro de las leyes pero siempre bien preparado y organizado ante cualquier circunstancia. Para evitar caer en lealtades personales o familiares, debe haber disposiciones institucionales que regulen y controlen el desempeño de los gobernantes. De esta forma, el estado puede funcionar incluso bajo gobernantes mediocres. La gente es naturalmente egoísta, así que un gobernante sensato no confía en que su pueblo intenta hacer el bien sino que se asegura de que no pueda hacer el mal.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Edad Media 2: islamic boogaloo - Filosofía árabe-persa&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Al-Kindi&lt;/strong&gt; (801, Irak - reconciliación entre filosofía y el islam): Para quien busca la verdad, nada es más importante que la verdad. La verdad ennoblece todo, y no debe ser despreciada ella ni a quien la pronuncia. La doctrina del Uno de Plotino explica que la realidad es una plenitud única: el universo emana de Dios, quien es eterno y no tiene partes sujetas a cambios.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Al-Farabi&lt;/strong&gt; (870, Kazajistán - universalidad de la filosofía): La lógica es universal, inherente en todos los idiomas y pensamientos. Esta universalidad la hace superior a la gramática, y por lo tanto también a la teología (fuertemente dependiente de la interpretación de los textos sagrados). &lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Avicena&lt;/strong&gt; (980, Uzbekistán - el universo como emanación de Dios): La función de la filosofía es "determinar la realidad de las cosas en tanto resulte posible para los seres humanos", haciendo que las tareas de un filósofo sean dos: una teórica de descubrir la verdad (conocimiento), y una práctica de hallar el bien (lo que se debe hacer). Las cosas que existen en el mundo lo hacen porque su existencia ha sido causada, son contingentes. Pero debe haber un ser no causado (necesario) como primera causa de todo: este es Dios, el bien y la belleza más perfectos, la cosa más deseable y digna de amarse. Y como Dios es un ser necesario que causa la existencia de todo lo demás, entonces la existencia de todo lo demás también es necesaria.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Al-Ghazali&lt;/strong&gt; (1057, Irán - la incoherencia de los filósofos): La mayoría de la gente cree lo que las figuras de autoridad dicen que hay que creer sin hacerse ningún cuestionamiento. Los filosofos dicen estar libres de las opiniones de las autoridades, pero en realidad solo cambiaron de lugar su prisión mental: son esclavos de la razón. La razón es limitada, y restringirse a usarla como la única herramienta para llegar a conclusiones deriva en una visión muy cerrada de la verdad: "la fé y la profecía son aceptar la existencia de una esfera más allá de la razón". Las relaciones entre causas y efectos no son necesarias, son solo aparentes y surgen de las expectativas humanas al habituarse a los acontecimientos. Como los enunciados de las escrituras son simbólicos y abiertos a interpretación, todas las ideas que no contradigan a las tres enseñanzas fundamentales (monoteísmo, profecías y enseñanzas de la vida después de la muerte) deben ser toleradas y evaluadas por sus méritos, incluso si son erróneas.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Averroes&lt;/strong&gt; (1126, España - la incoherencia de la incoherencia): No todos son intelectualmente capaces de entender filosofía (o al menos no tienen voluntad para hacerlo), por lo que la religión cumple el rol de brindar una versión más fácil de digerir de la verdad por medio de la fé. Hay muy pocos textos en las escrituras cuyo significado está realmente consensuado, así que la filosofía y la religión deben convivir. Al-Ghazali se equivoca al prohibir ciertos debates: las escrituras siempre deben ser interpretadas simbólicamente cuando colisionan con la filosofía. Por ejemplo, la idea de un universo eterno es compatible con un Dios trascendente si se considera que la forma del universo fue impuesta en un momento determinado.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Un rayo de luz en medio de la opresion colonial - Filosofía africana&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Zara Yacob&lt;/strong&gt; (1599, Etiopía - el ilustrado de la cueva): La observación racional e individual del mundo y la gente es el método para revelar el propósito de Dios, no las creencias y las escrituras de las doctrinas religiosas. Dios nos creó imperfectos, de modo que la recompensa divina solo es digna tras la búsqueda de la perfección.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Jordan Kush Ngubane&lt;/strong&gt; (1917, Sudáfrica - defensor del Ubuntu): Somos seres sociales que se necesitan mutuamente, y debemos vivir de acuerdo a eso. El deber queda implícito en el ser: el hecho de ser humano implica una obligatoria reciprocidad que interconecta y constituye a la humanidad. Ubuntu significa "soy porque somos".&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;</content><category term="Filosofía"></category></entry><entry><title>Medieval and renaissance philosophy</title><link href="https://facuroffet99.github.io/en/notes/philosophy_3.html" rel="alternate"></link><published>2025-06-19T15:08:00-03:00</published><updated>2025-06-19T15:08:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-06-19:/en/notes/philosophy_3.html</id><summary type="html">&lt;p&gt;Personal notes on non-Western philosophy: Indian schools (Buddhism, Jainism, Samkhya), Chinese philosophy (Confucius, Laozi, Zhuangzi), and Arab-Persian philosophy (Avicenna, Averroes, Al-Ghazali). Based on A.C. Grayling and the Philosophize This! podcast.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Non-western philosophy&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;These are my personal notes from Part 5 of the book &lt;a href="https://www.google.com.ar/books/edition/The_History_of_Philosophy/tkvRvQEACAAJ?hl=es-419"&gt;The History of Philosophy&lt;/a&gt; by A.C. Grayling, and from episodes 7–9, 18, and 19 of the podcast &lt;a href="https://open.spotify.com/show/2Shpxw7dPoxRJCdfFXTWLE"&gt;Philosophize This!&lt;/a&gt; by Stephen West. This is by no means a comprehensive analysis of the philosophy of the rich Eastern cultures, but rather a quick overview of their most influential figures.&lt;/p&gt;
&lt;p&gt;I introduce each philosopher in the format &lt;em&gt;Name (Year, Place – Description)&lt;/em&gt;. Year refers to the birth year (or approximate, as many dates are uncertain), and Place refers to the modern country of their birth city. In the Description, I highlight what I personally consider to be either their main contribution or a detail that helps me remember them.&lt;/p&gt;
&lt;p&gt;In the case of Indian philosophy, it's more appropriate to group ideas into schools rather than discuss individual philosophers.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Suffering comes fast, but we are faster – Indian philosophy&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Samkhya School&lt;/strong&gt; (liberated consciousness): There is a dualism between &lt;em&gt;purusha&lt;/em&gt; (pure consciousness) and &lt;em&gt;prakriti&lt;/em&gt; (everything that is not consciousness). &lt;em&gt;Prakriti&lt;/em&gt; is stable when its three qualities—roughly light, darkness, and motion—are in balance. &lt;em&gt;Purusha&lt;/em&gt; is ontologically superior to &lt;em&gt;prakriti&lt;/em&gt;, and liberation is realizing this: we are not bound to &lt;em&gt;prakriti&lt;/em&gt; because &lt;em&gt;purusha&lt;/em&gt; has always been free.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Yoga School&lt;/strong&gt; (meditation): Adheres to Samkhya metaphysics but adds practical components: consciousness is the primary existent, and its deepest level of liberation can be accessed through posture, breathwork, and meditation techniques.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Nyaya-Vaisheshika School&lt;/strong&gt; (logic to categorize things): To exist is to be knowable and nameable via sensory perception, inference, comparison, and expert testimony. Everything is made of indivisible, eternal, and entirely distinct atoms, which combine to form impermanent substances. The relation binding a substance (a leaf) to a property (its color) is just as real as the components: inherence is something that lies between part and whole. Effects are not contained in causes but newly created by them.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Purva Mimamsa / Karma Mimamsa School&lt;/strong&gt; (ritualism): Scriptures are the only reliable source of knowledge; their authority is absolute and must be trusted without question. If rituals and sacrifices are not performed as required, the universe suffers adverse consequences.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Vedanta / Uttara Mimamsa School&lt;/strong&gt; (self-existence relation): The path to liberation lies in understanding the relationship between the individual self (&lt;em&gt;atman&lt;/em&gt;) and ultimate reality (&lt;em&gt;Brahman&lt;/em&gt;). Various sub-schools offer different interpretations: the two may be identical, one part of the other, or entirely distinct.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Charvaka / Lokayata School&lt;/strong&gt; (radical empiricism): Sensory perception is the only valid source of knowledge. It tells us nothing about reincarnation or the value of rituals, so there’s no reason to believe in them. The only real thing is the material world, so seeking pleasure and avoiding pain are good.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Buddhism&lt;/strong&gt; (ego suppression): The future isn’t controlled by supernatural gods—destiny is entirely self-dependent. Liberation of the soul shouldn't be sought, because there is no soul; the “self” is an illusion. Four noble truths exist: &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1: Suffering is universal, and dissatisfaction is the mind’s default state (satisfaction exists, but always fades). &lt;/li&gt;
&lt;li&gt;2: Dissatisfaction is caused by desire and expectations, which come from ego and the illusion of separateness. &lt;/li&gt;
&lt;li&gt;3: Suffering can be ended by eliminating desire—this requires eliminating the ego (achieving Nirvana). &lt;/li&gt;
&lt;li&gt;4: The path to Nirvana—and escape from the cycle of suffering and rebirth (&lt;em&gt;samsara&lt;/em&gt;)—is through morality (speech, action, lifestyle), meditation (effort, awareness, concentration), and wisdom (understanding, resolve).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Jainism&lt;/strong&gt; (perspectivism): Liberation comes from escaping the cycle of rebirth through nonviolence, detachment, asceticism, and the belief that reality is multifaceted and infinitely complex. Because of this, no single or absolute description is fully true—multiple partial viewpoints exist.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Let it all flow, but please keep it tidy – Chinese philosophy&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Laozi&lt;/strong&gt; (571 BCE, China – Daoism): There is a path to unlocking one’s life force, and it is the &lt;em&gt;Dao&lt;/em&gt;. Language fails to describe it: “The Dao that can be spoken is not the eternal Dao.” The Dao transcends understanding: it is everything, the source of existence, the void around things, and also nothingness. One follows the Dao through &lt;em&gt;wuwei&lt;/em&gt;: effortless action, letting things run their course. “The sage acts effortlessly, teaches without words, creates without claiming, gives without expecting, and thus has nothing to lose.”&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Confucius&lt;/strong&gt; (551 BCE, China – respect for tradition): The ideal ruler leads by moral example, like a father to his children. A disciplined, benevolent life comes from respectfully following the rituals passed down by authority figures. To be good, one must first distinguish between good and bad people: “Don’t do to others what you wouldn’t want done to you.” The key is continual self-improvement, avoiding complacency.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Mozi&lt;/strong&gt; (468 BCE, China – utilitarian love): We should love and value others as ourselves to safeguard social harmony and peace. We must constantly weigh benefits and harms, avoiding the mistake of confusing what’s common with what’s right, and custom with correctness.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Zhuangzi&lt;/strong&gt; (369 BCE, China – the journey over the goal): We thrive when our lives are simple and close to nature. Life is short and knowledge is limitless, so chasing knowledge is futile. When pursuing knowledge, each day you add to your life; when following the Dao, each day you remove. But more important than following the Dao is experiencing it: the ideal is to wander through the path.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Xun Zi&lt;/strong&gt; (313 BCE, China – the standardizer): Humans are greedy by nature and inclined to selfishness, so goodness requires conscious effort. Goodness is artificial, a cultural product—education and moral role models are necessary for virtue. Since names are conventional and context-dependent, rulers must define them by decree to ensure law and order. Rituals, too, should be standardized to promote social discipline.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Han Fei&lt;/strong&gt; (280 BCE, China – legalism): A ruler’s priority is not the people’s wellbeing but maintaining order and power via law and punishment. The ruler should appear passive, hidden behind a wall of laws but always prepared and organized. To avoid personal favoritism, systems must regulate and monitor officials. This way, the state functions even under mediocre rulers. People are naturally selfish, so a wise ruler ensures they &lt;em&gt;can’t&lt;/em&gt; do wrong rather than trusting they’ll &lt;em&gt;want&lt;/em&gt; to do right.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Middle Ages 2: Islamic Boogaloo – Arab-Persian philosophy&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Al-Kindi&lt;/strong&gt; (801, Iraq – reconciliation of philosophy and Islam): For a truth-seeker, nothing matters more than truth. Truth ennobles everything and should not be dismissed—nor should the person who speaks it. Plotinus’s “One” explains that reality is a unified fullness: the universe emanates from God, who is eternal and changeless.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Al-Farabi&lt;/strong&gt; (870, Kazakhstan – philosophy’s universality): Logic is universal, present in all languages and thought. This makes it superior to grammar—and thus to theology, which heavily depends on interpreting sacred texts.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Avicenna&lt;/strong&gt; (980, Uzbekistan – the universe as God's emanation): Philosophy’s role is “to determine the reality of things, as far as humanly possible.” Thus, philosophers have two tasks: theoretical (seeking truth) and practical (finding the good). Everything that exists does so because it was caused—contingent things must have a necessary, uncaused cause: God, the ultimate good and beauty, the most lovable being. Since God necessarily causes all else, everything else must necessarily exist.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Al-Ghazali&lt;/strong&gt; (1057, Iran – the incoherence of philosophers): Most people accept what authorities say without question. Philosophers claim to be free of dogma, but are still mentally imprisoned—now by reason. Reason is limited, and relying solely on it leads to a narrow truth: “Faith and prophecy are the acceptance of a realm beyond reason.” Cause-effect relationships are not necessary, just habitual expectations. Since scripture is symbolic and open to interpretation, any ideas not contradicting the core three teachings (monotheism, prophecy, and life after death) should be tolerated and judged on their merits—even if wrong.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Averroes&lt;/strong&gt; (1126, Spain – the incoherence of the incoherence): Not everyone is capable (or willing) to grasp philosophy, so religion offers a more digestible version of truth via faith. Few scriptural passages have fixed meanings; philosophy and religion must coexist. Al-Ghazali is wrong to forbid certain debates: scripture must always be interpreted symbolically when in conflict with philosophy. For instance, an eternal universe is compatible with a transcendent God if we accept that its form was imposed at a specific moment.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;A ray of light amid colonial oppression – African philosophy&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Zara Yacob&lt;/strong&gt; (1599, Ethiopia – the enlightened one in the cave): Rational, individual observation of the world and people is the method to reveal God's purpose—not doctrines or sacred texts. God made us imperfect, so divine reward is only worthy after a quest for perfection.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Jordan Kush Ngubane&lt;/strong&gt; (1917, South Africa – Ubuntu defender): We are social beings who need one another and should live accordingly. Duty is implied in being: to be human is to be bound in mutual responsibility, which connects and defines our humanity. &lt;em&gt;Ubuntu&lt;/em&gt; means: “I am because we are.”&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;</content><category term="Philosophy"></category></entry><entry><title>Filosofía medieval y renacentista</title><link href="https://facuroffet99.github.io/notes/philosophy_2.html" rel="alternate"></link><published>2025-06-04T17:09:00-03:00</published><updated>2025-06-04T17:09:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-06-04:/notes/philosophy_2.html</id><summary type="html">&lt;p&gt;Notas personales sobre filosofía medieval y renacentista: escolásticos como Agustín, Tomás de Aquino y Ockham, y pensadores del Renacimiento como Maquiavelo y Montaigne. Basadas en A.C. Grayling y el podcast Philosophize This!&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Filosofía medieval y renacentista&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;Estas son mis notas personales de la Parte 2 del libro &lt;a href="https://www.google.com.ar/books/edition/The_History_of_Philosophy/tkvRvQEACAAJ?hl=es-419"&gt;Historia de la Filosofía&lt;/a&gt; de A.C. Grayling, y de los episodios 16, 17 y 20 a 24 del podcast &lt;a href="https://open.spotify.com/show/2Shpxw7dPoxRJCdfFXTWLE"&gt;Philosophize This!&lt;/a&gt; de Stephen West. &lt;/p&gt;
&lt;p&gt;Introduzco a cada filósofo con el formato &lt;em&gt;Nombre (Año, Lugar - Descripción)&lt;/em&gt;. Año se corresponde con el año de nacimiento (o su aproximado, hay fechas que no se saben con seguridad), y Lugar con el país actual de su ciudad de nacimiento. En Descripción subrayo bien lo que yo considero es el aporte principal del filósofo o bien un suceso que me haga recordarlo fácilmente.&lt;/p&gt;
&lt;p&gt;Hay veces en que es más conveniente agrupar a los filósofos en escuelas que detallar sus contribuciones individuales. En esos casos, el formato es &lt;em&gt;Escuela - Descripción [Nombre1 (Año1, Lugar1), Nombre2 (Año2, Lugar2), ...]&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;A merced de la ortodoxia cristiana - Los escolásticos&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Agustín de Hipona&lt;/strong&gt; (354, Argelia - atormentado por su pasado de pecador): Existen dos tipos de males. Uno es el que Dios permite como castigo por nuestros pecados o como generador de un bien mayor. El otro es el mal que hace la gente al pecar, que surge del abuso del libre albedrío que Dios nos dió: "en tanto que los hombres que no pecan obtienen felicidad, el universo es perfecto; cuando los pecadores son infelices, el universo es perfecto". Todo mal, directa o indirectamente, es causado por las personas: el mal es la ausencia de bien por lo que es ajeno a Dios. Desde que nacemos todos cometemos pecados (lo sepamos o no), por eso que necesitamos a Dios para que nos salve de nuestro inevitable destino en el infierno. El tiempo solo existe en relación a la forma en que la mente humana percibe la realidad y le da sentido a lo que la rodea. Dios creó al tiempo y existe por fuera de él, comprendiendo todo en una eterna presciencia.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Boecio&lt;/strong&gt; (480, Italia - consolado por la filosofía tras su sentencia de muerte): Hay una diferencia entre conocimiento divino y predeterminación: que Dios conozca las cosas que ya pasaron, están pasando y pasarán no significa que haya forjado un destino para cada uno de nosotros del que no podemos desviarnos. Lo que para los humanos es pasado, presente y futuro, para Dios solo es presente. La felicidad y la bondad son una misma cosa que no surge de la posesión de bienes mundanos (riqueza, poder) sino de la posesión de bienes auténticos (virtud, amor). Por lo tanto, los malvados (quienes no poseen bondad) son necesariamente infelices. Aunque no lo parezca en el momento, el sufrimiento y la infelicidad de los buenos tienen un propósito más elevado: todo lo que ocurre es la voluntad de Dios. Los propiedades de las cosas particulares no tienen una existencia independiente: no existe la rojez pero sí las cosas que son rojas.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Anselmo de Canterbury&lt;/strong&gt; (1033, Inglaterra - lógica llevada al extremo): Hay cosas que solo existen en la mente humana, cosas que solo existen en la realidad y cosas que existen en ambas. Dios es el concepto mental de la cosa más concebiblemente grande que hay. Pero como existir en la realidad y en la mente es "más grande" que solo existir en la mente, Dios necesariamente también tiene que existir en la realidad (argumento ontológico). Suponer que la verdad no ha existido siempre también conlleva a una contradicción similar: implica que antes de que ella existiera, era verdad que no existía la verdad. Por lo tanto, la verdad siempre ha existido.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pedro Abelardo&lt;/strong&gt; (1079, Francia - nominalismo y deontología): Todo lo que existe es individual y particular: los universales son solo nombres que asignamos por comodidad para poder agrupar cosas que son similares (perros) o que poseen características similares (rojez). Que una acción sea buena o mala depende únicamente de las intenciones del actor: las consecuencias de una acción son moralmente irrelevantes si las intenciones derivan del amor a Dios y el deseo de obedecerlo.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Roger Bacon&lt;/strong&gt; (1214, Inglaterra - un moderno antes de la modernidad): Las teorías obtenidas por medio de la razón deben ser verificadas con datos sensoriales e instrumentales. El error se origina como un exceso de confianza en las costumbres y la opinión popular. La verdad reside en la revelación general de Dios a lo largo de la historia, por lo que el estudio de las lenguas de otras civilizaciones es necesario para una educación completa. El lenguaje es un sistema que permite, por medio de signos ajenos a la información que contienen, transmitir pensamientos de un pensador a un receptor.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Tomás de Aquino&lt;/strong&gt; (1224, Italia - la razón como medio de adopción de la fe cristiana): La esencia de una cosa es un compuesto de materia y forma sustancial. La materia puede cambiar, pero es la forma sustancial la que determina lo que la cosa es. Además, una cosa posee formas accidentales que no contribuyen a su esencia, como el color de una hoja, que puede cambiar sin que esta deje de ser una hoja. En el caso del ser humano, su forma sustancial es el alma, que realiza funciones que no dependen de los órganos del cuerpo, como la razón y la voluntad. El alma es incorruptible, es decir, no es susceptible al cambio, y por eso sobrevive a la muerte. Sin embargo, no constituye por sí sola una sustancia completa, ya que el ser humano es una unidad de alma y cuerpo. Al operar sobre la información adquirida por los sentidos, el alma humana —dotada de un poder intelectual activo— hace posible el conocimiento. La existencia de Dios no es un conocimiento inmediato o intuitivo, pero puede demostrarse a partir de la observación del mundo sensible: todo lo que existe tiene una causa, por lo que debe existir una causa primera que no haya sido causada, que es Dios (argumento cosmológico).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Duns Escoto&lt;/strong&gt; (1266, Escocia - univocidad del ser): No hay una distinción tajante entre existencia y esencia. La materia puede existir sin forma (materia prima) y viceversa (seres espirituales). La razón por sí misma no alcanza para conocer la naturaleza de Dios, sino que la revelación es una condición necesaria. La voluntad es superior al intelecto. &lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Guillermo de Ockham&lt;/strong&gt; (1285, Inglaterra - navaja de Ockham): A la hora de dar una explicación, no hay que hacer más suposiciones de las necesarias: en igualdad de condiciones, una teoría simple es más preferible que una compleja. Las verdades teológicas solo se pueden comprender a través de la fe, por lo que no puede haber pruebas de la existencia de Dios: "los caminos de Dios no están abiertos a la razón, pues Él ha creado al mundo y dispuesto la vía a la salvación independientes de toda ley de lógica o racionalidad que los humanos puedan descubrir". Dios es el único ser necesario del universo, todo lo demás debe descubrirse por medio de la investigación. La iglesia y el estado poseen la misma jerarquía pero difieren en sus esferas de responsabilidad, por lo que deben mantenerse por separado. La voluntad es independiente tanto del intelecto como de los apetitos naturales, de forma que puede elegir incluso lo que no parece bueno.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Volvamos a preocuparnos por la vida que tenemos ahora en vez de por la próxima - El Renacimiento&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Humanismo&lt;/strong&gt; (dignidad humana) - [Francesco Petrarca (1304, Italia), Nicolás de Cusa (1401, Alemania), Marsilio Ficino (1433, Italia), Pico della Mirandola (1463, Italia), Charles de Bovelles (1475, Francia)]: En lugar de lamentarnos por las miserias del hombre, debemos celebrar la dignidad humana. No tenemos las ventajas naturales de los animales (garras, rapidez, caparazones), pero sí poseemos los dones de la inteligencia y la creatividad. Estos nos permiten explotar las ventajas de los animales: somos reflejos divinos capaces de comprender y transformar el mundo. El ser humano puede moldearse a si mismo, puede ser lo que desee ser y puede ocupar cualquier posición en el esquema de las cosas: conocerse a sí mismo es conocer algo elevado. Si bien la auténtica felicidad es la vida eterna en presencia de Dios, en este mundo se puede lograr un reflejo imperfecto de la suprema felicidad póstuma. Los conceptos maduros de la filósofía pagana pueden aplicarse a la vida en este mundo, pero los asuntos de la siguiente vida deben dejarse en manos de las escrituras. El estado no debe buscar solo la paz, sino también la fama, el honor y la gloria por medio del impulso del arte y la cultura. Hacerlo mediante la guerra es algo bestial e indigno de la humanidad civilizada. &lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Erasmo de Rotterdam&lt;/strong&gt; (1466, Países Bajos - la via media): La fé debe ser un asunto personal centrado en amarnos los unos a los otros, lejos de los rituales arbitrarios y las disputas sin sentido de la escolástica. La iglesia debe volver a las fuentes originales del cristianismo (las escrituras) y aprender de las enseñanzas de los grandes filósofos paganos. Ser ignorante a la verdad no te hace ser miserable; nacimos en la ignorancia y ella es parte de lo que significa ser un ser humano.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Nicolás Maquiavelo&lt;/strong&gt; (1469, Italia - mantenere lo stato): No hay una manera intrínsecamente correcta de actuar porque el bien y el mal son definidos después del hecho de acuerdo a un objetivo que se intenta alcanzar. Si bien la persona promedio debe ser honesta, templada, etc, eso no aplica a los buenos gobernantes de una sociedad ya que los objetivos a los que se enfrentan son muy distintos: oponentes menos escrupulosos se aprovecharían de gobernantes que solo intentasen gobernar por medio de la virtud. La estabilidad del estado tiene que ser el objetivo final del buen gobernante, y debe hacer todo lo que esté a su alcance para mantenerla: "el fin justifica los medios". Las dos principales herramientas disponibles son la ley y la fuerza, y el mejor gobernante es el que sabe elegir cómo y cuándo aplicar cada una. Cómo existe la posibilidad de que un gobernante sea malo y sus intereses no coincidan con los del estado que gobierna, el pueblo debe estar armado (guardián de su propia libertad) y ser implacable cuando la situación lo amerite: la estabilidad del estado debe mantenerse siempre.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Michel de Montaigne&lt;/strong&gt; (1533, Francia - experiencia cercana a la muerte): La mayoría de las generalizaciones hechas por los humanos no son útiles porque eventualmente se prueba que son erróneas, así que no hay que perder el tiempo buscando reglas que se apliquen a todos los casos. La visión más productiva del mundo debe ser una que esté basada en nuestro propio conjunto de experiencias previas: uno no puede estar seguro de que los demás experimenten las cosas de la misma forma. No debemos agonizar sobre cosas que no podemos saber: "aprender a filosofar es aprender a morir".&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;</content><category term="Filosofía"></category></entry><entry><title>Medieval and renaissance philosophy</title><link href="https://facuroffet99.github.io/en/notes/philosophy_2.html" rel="alternate"></link><published>2025-06-04T17:09:00-03:00</published><updated>2025-06-04T17:09:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-06-04:/en/notes/philosophy_2.html</id><summary type="html">&lt;p&gt;Personal notes on medieval and Renaissance philosophy: scholastics such as Augustine, Thomas Aquinas, and Ockham, and Renaissance thinkers including Machiavelli and Montaigne. Based on A.C. Grayling and the Philosophize This! podcast.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Medieval and renaissance philosophy&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;These are my personal notes from Part 2 of the book &lt;a href="https://www.google.com.ar/books/edition/The_History_of_Philosophy/tkvRvQEACAAJ?hl=es-419"&gt;The History of Philosophy&lt;/a&gt; by A.C. Grayling, and from episodes 16, 17 and 20 to 24 of the podcast &lt;a href="https://open.spotify.com/show/2Shpxw7dPoxRJCdfFXTWLE"&gt;Philosophize This!&lt;/a&gt; by Stephen West.&lt;/p&gt;
&lt;p&gt;I introduce each philosopher using the format &lt;em&gt;Name (Year, Place – Description)&lt;/em&gt;. Year refers to the year of birth (or an approximation, as some dates are uncertain), and Place refers to the current country of their city of birth. In the Description, I highlight either what I consider the philosopher’s main contribution or a memorable trait that helps me recall them easily.&lt;/p&gt;
&lt;p&gt;Sometimes it's more helpful to group philosophers by schools of thought rather than detailing their individual contributions. In such cases, the format is &lt;em&gt;School – Description [Name1 (Year1, Place1), Name2 (Year2, Place2), ...]&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;At the mercy of christian orthodoxy – The scholastics&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Augustine of Hippo&lt;/strong&gt; (354, Algeria – tormented by his sinful past): There are two types of evil. One is permitted by God as punishment for our sins or as the source of a greater good. The other is the evil people do when they sin, which comes from abusing the free will that God gave us: “as long as those who do not sin attain happiness, the universe is perfect; and when sinners are unhappy, the universe is perfect.” All evil, directly or indirectly, is caused by people: evil is the absence of good and thus foreign to God. From birth, we all sin (whether we know it or not), which is why we need God to save us from our inevitable fate in hell. Time exists only in relation to how the human mind perceives reality and gives meaning to what surrounds it. God created time and exists outside of it, comprehending everything in eternal foreknowledge.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Boethius&lt;/strong&gt; (480, Italy – consoled by philosophy after his death sentence): There is a difference between divine knowledge and predestination: just because God knows everything that has happened, is happening, and will happen, does not mean that He has forged an unchangeable destiny for each of us. What is past, present, and future to us is only present to God. Happiness and goodness are the same thing and do not arise from possessing worldly goods (wealth, power) but from possessing authentic goods (virtue, love). Therefore, the wicked (who lack goodness) are necessarily unhappy. Even if it doesn’t seem so at the moment, the suffering and unhappiness of good people have a higher purpose: everything that happens is the will of God. The properties of particular things do not have an independent existence—“redness” does not exist, but red things do.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Anselm of Canterbury&lt;/strong&gt; (1033, England – logic taken to the extreme): Some things exist only in the human mind, some exist only in reality, and some exist in both. God is the mental concept of the greatest thing conceivable. But since existing in reality and the mind is “greater” than existing only in the mind, God must also exist in reality (ontological argument). Assuming that truth has not always existed leads to a similar contradiction: it implies that before truth existed, it was true that truth did not exist. Therefore, truth has always existed.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Peter Abelard&lt;/strong&gt; (1079, France – nominalism and deontology): Everything that exists is individual and particular: universals are only names we assign for convenience to group similar things (dogs) or things with similar features (redness). Whether an action is good or bad depends solely on the intentions of the actor: the consequences of an action are morally irrelevant if the intentions stem from love of God and the desire to obey Him.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Roger Bacon&lt;/strong&gt; (1214, England – a modern mind before modernity): Theories derived through reason must be verified with sensory and instrumental data. Error originates from excessive trust in customs and popular opinion. Truth lies in God's general revelation throughout history, so studying the languages of other civilizations is necessary for a complete education. Language is a system that allows the transmission of thoughts from one thinker to a receiver using signs that are independent from the information they carry.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Thomas Aquinas&lt;/strong&gt; (1224, Italy – reason as a path to adopt christian faith): The essence of a thing is a compound of matter and substantial form. Matter can change, but the substantial form determines what the thing is. A thing also has accidental forms that do not contribute to its essence, such as the color of a leaf, which can change without it ceasing to be a leaf. In the case of humans, the substantial form is the soul, which performs functions independent of bodily organs, such as reason and will. The soul is incorruptible—that is, unchangeable—and thus survives death. However, it is not a complete substance on its own, as the human being is a unity of body and soul. When processing information acquired through the senses, the human soul—endowed with an active intellect—makes knowledge possible. The existence of God is not an immediate or intuitive knowledge, but it can be demonstrated from observation of the sensible world: everything that exists has a cause, so there must be a first cause that is itself uncaused—God (cosmological argument).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Duns Scotus&lt;/strong&gt; (1266, Scotland – univocity of being): There is no sharp distinction between existence and essence. Matter can exist without form (prime matter) and vice versa (spiritual beings). Reason alone is insufficient to know the nature of God; revelation is a necessary condition. The will is superior to the intellect.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;William of Ockham&lt;/strong&gt; (1285, England – Ockham’s razor): When giving an explanation, one must not make more assumptions than necessary: all else being equal, a simple theory is preferable to a complex one. Theological truths can only be understood through faith, so there can be no proofs of God’s existence: “the ways of God are not open to reason, for He created the world and the path to salvation independent of any logic or rationality that humans might discover.” God is the only necessary being in the universe; everything else must be discovered through investigation. Church and state are of equal rank but differ in their spheres of responsibility, and thus must remain separate. The will is independent of both the intellect and natural appetites, and can choose even what does not appear good.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Let’s worry about the life we have now instead of the next one – The Renaissance&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Humanism&lt;/strong&gt; (human dignity) – [Francesco Petrarch (1304, Italy), Nicholas of Cusa (1401, Germany), Marsilio Ficino (1433, Italy), Giovanni Pico della Mirandola (1463, Italy), Charles de Bovelles (1475, France)]: Instead of lamenting humanity’s miseries, we should celebrate human dignity. We lack the natural advantages of animals (claws, speed, shells), but we possess the gifts of intelligence and creativity. These allow us to exploit the advantages of animals: we are divine reflections capable of understanding and transforming the world. Humans can shape themselves, become what they want, and occupy any position in the order of things: knowing oneself is knowing something exalted. While true happiness lies in eternal life in God's presence, in this world we can achieve an imperfect reflection of that supreme posthumous happiness. The mature concepts of pagan philosophy can be applied to life in this world, but matters of the next life should be left to the Scriptures. The state should seek not only peace, but also fame, honor, and glory through the promotion of art and culture. To pursue this through war is beastly and unworthy of civilized humanity.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Erasmus of Rotterdam&lt;/strong&gt; (1466, Netherlands – the middle way): Faith must be a personal matter focused on loving one another, far from arbitrary rituals and meaningless scholastic disputes. The Church should return to the original sources of Christianity (the Scriptures) and learn from the teachings of the great pagan philosophers. Being ignorant of the truth does not make one miserable; we are born in ignorance, and it is part of what it means to be human.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Niccolò Machiavelli&lt;/strong&gt; (1469, Italy – mantenere lo stato): There is no intrinsically correct way to act because good and evil are defined after the fact based on the goal being pursued. While the average person should be honest, temperate, etc., this does not apply to good rulers, whose goals are very different: unscrupulous opponents would exploit rulers who tried to govern only through virtue. The stability of the state must be the ultimate goal of a good ruler, and they must do whatever it takes to preserve it: “the end justifies the means.” The two main tools available are law and force, and the best ruler is the one who knows how and when to apply each. Since a ruler might be wicked and have interests that don’t align with the state’s, the people must be armed (guardians of their own freedom) and relentless when the situation calls for it: the stability of the state must always be preserved.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Michel de Montaigne&lt;/strong&gt; (1533, France – near-death experience): Most generalizations made by humans are not useful because they eventually turn out to be wrong, so we should not waste time seeking rules that apply to all cases. The most productive worldview is one based on our own set of prior experiences: one cannot be sure that others experience things the same way. We should not agonize over things we cannot know: “to learn how to philosophize is to learn how to die.”&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;</content><category term="Philosophy"></category></entry><entry><title>Filosofía de la antigüedad</title><link href="https://facuroffet99.github.io/notes/philosophy_1.html" rel="alternate"></link><published>2025-05-21T11:35:00-03:00</published><updated>2025-05-21T11:35:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-05-21:/notes/philosophy_1.html</id><summary type="html">&lt;p&gt;Notas personales sobre filosofía antigua: presocráticos, Sócrates, Platón y Aristóteles, y las escuelas estoica, epicúrea, cínica, escéptica y neoplatónica. Basadas en A.C. Grayling y el podcast Philosophize This!&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Filosofía de la antigüedad&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;Estas son mis notas personales de la Parte 1 del libro &lt;a href="https://www.google.com.ar/books/edition/The_History_of_Philosophy/tkvRvQEACAAJ?hl=es-419"&gt;Historia de la Filosofía&lt;/a&gt; de A.C. Grayling, y de los episodios 1 a 6 y 10 a 15 del podcast &lt;a href="https://open.spotify.com/show/2Shpxw7dPoxRJCdfFXTWLE"&gt;Philosophize This!&lt;/a&gt; de Stephen West. &lt;/p&gt;
&lt;p&gt;Introduzco a cada filósofo con el formato &lt;em&gt;Nombre (Año, Lugar - Descripción)&lt;/em&gt;. Año se corresponde con el año de nacimiento (o su aproximado, hay fechas que no se saben con seguridad), y Lugar con el país actual de su ciudad de nacimiento. En Descripción subrayo bien lo que yo considero es el aporte principal del filósofo o bien un suceso que me haga recordarlo fácilmente.&lt;/p&gt;
&lt;p&gt;Hay veces en que es más conveniente agrupar a los filósofos en escuelas que detallar sus contribuciones individuales. En esos casos, el formato es &lt;em&gt;Escuela - Descripción [Nombre1 (Año1, Lugar1), Nombre2 (Año2, Lugar2), ...]&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Los filósofos antes de la filosofía - Los presocráticos&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Tales de Mileto&lt;/strong&gt; (624 aC, Turquía - el inicio): Primero en usar explicaciones racionales que no involucran dioses. El arjé (aquello de lo que todo existe está compuesto) es el agua. El alma es la causa de movimiento.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Anaximandro&lt;/strong&gt; (610 aC, Turquía - primera realidad no material): El arjé no es algo material, el arjé es el infinito. El infinito es la causa universal de generación y destrucción del universo; el infinito restaura las leyes naturales cuando se ven alteradas.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Anaxímenes&lt;/strong&gt; (590 aC, Turquía - primera teoría sistemática): El arjé es el aire, que da forma a las cosas al rarificarse ("expandirse") o condensarse ("comprimirse").&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pitágoras&lt;/strong&gt; (570 aC, Grecia - culto a la matemática y la música): Todo se puede entender a través de los números. El objetivo de la vida es terminar el ciclo de sufrimiento y reencarnación, para finalmente vivir libre y eternamente en un reino bendito. El humano es malo en parte, y la única forma de purgarse es vivir una vida de restricción y contemplación hacia la matemáticas, la música y la astronomía. Entender esos tres campos significa entender las leyes eternas del universo, y vivir en armonía con ellas es lo más cercano a la inmortalidad posible. Llegar a conclusiones por medio de la razón es superior que por medio de los sentidos.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Jenófanes&lt;/strong&gt; (560 aC, Turquía - la religión como proyección de los defectos humanos): Rechazo a la religión tradicional y sus antropomórficas deidades olímpicas: los fenómenos naturales deben ser investigados y comprendidos. Los humanos atribuimos a los dioses todas nuestras características que nos avergüenzan para sentirnos mejor con nosotros mismos. Primero en decir que Dios es el todo.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Heráclito&lt;/strong&gt; (535 aC, Turquía - el enigmático): Hay una ley cósmica (logos) que gobierna todo. Todo está en un estado permanente de cambio: "no podés entrar dos veces a un mismo río". El arjé es el fuego.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Parménides&lt;/strong&gt; (530 aC, Italia - lo que es es y lo que no es no es): Nada puede salir de la nada, por lo que el cambio es imposible. El universo es un todo eterno, por lo que no existe el espacio vacío y todo cambio es una ilusión. Solo existe lo que puede ser pensado; lo real es lo mismo que lo concebible.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Anaxágoras&lt;/strong&gt; (500 aC, Turquía - elementos infinitos): Existe una variedad infinita de elementos fundamentales (semillas) que están presentes en todo a la vez: las cosas individuales se diferencian entre sí solo por la preponderancia (no ausencia) de unos elementos sobre otros. El principio ordenador del universo es una cosa inmaterial e inteligente que proporciona eficacia causal ("poder sobre") a los elementos.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Empédocles&lt;/strong&gt; (495 aC, Italia - un dios entre los mortales): El arjé son cuatro elementos eternos e inmutables (aire, fuego, agua y tierra) que se combinan en distintas proporciones para conformar el mundo que vemos. Hay dos fuerzas fundamentales en el universo que están en continua batalla cíclica, lo que resulta en cambios en el mundo: amor combina los elementos y lucha los separa.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Zenón de Elea&lt;/strong&gt; (490 aC, Italia - Aquiles y la tortuga): El movimiento es una ilusión: no se puede pasar por una cantidad infinita de puntos en un lapso finito de tiempo. La apariencia no es necesariamente la realidad.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Demócrito&lt;/strong&gt; (460 aC, Grecia - atomismo): Todo está compuesto de átomos (objetos diminutos e indivisibles) y espacio vacío. Los átomos no cambian pero su configuración si, generando infinitas instancias de una única realidad. Existe un determinismo cósmico; sabiendo las condiciones iniciales de un átomo y con suficiente poder de cálculo se puede saber todo su futuro.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Sofistas&lt;/strong&gt; (maestros de la oratoria y la retórica)- [Protágoras (485 aC, Grecia), Gorgias (480 aC, Italia), Pródico (465 aC, Grecia), Hipias (443 aC, Grecia), Antifonte (480 aC, Grecia), Critias (460 aC, Grecia)]: Todos los debates tienen dos lados, y ninguno es más o menos acertado que el otro. Se puede influenciar a la gente hacia cualquier extremo solo siendo lo suficientemente persuasivo. Es la persona que mantiene una opinión lo que mide su valor, no la opinión en sí o los hechos en los que se basa: "el hombre es la medida de todas las cosas". Lo que es cierto o correcto para una persona puede no serlo para otra; todo es subjetivo.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;La santísima trinidad - Sócrates, Platón y Aristóteles&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Sócrates&lt;/strong&gt; (470 aC, Grecia - método de la refutación): Llevó la filosofía al pueblo, haciendo que la gente cuestionase lo que sabía y guiándola al camino de la verdad: "bien, ahora que sabes que no sabes de qué estás hablando podemos empezar a hacer progresos". La filosofía es discusión, cuestionamiento y argumentación. La única forma de vivir una vida virtuosa es saber las verdaderas definiciones de las palabras virtuosas, y la única forma de saberlas es a través de la razón. La búsqueda del conocimiento es el objetivo final de la vida y la verdadera virtud; una vida no examinada no vale la pena ser vivida.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Platón&lt;/strong&gt; (427 aC, Grecia - mundo de las formas): Los conceptos como justicia y belleza no están definidos por la percepción de la gente que los percibe, sino que son eternos, perfectos e inmutables. Lo mismo pasa con todos los objetos físicos. Estas versiones perfectas de las definiciones no existen en el mundo sensible en el que vivimos, sino que existen en un mundo de formas completamente separado de nuestra realidad. Lo que percibimos son meras copias imperfectas e inferiores en constante cambio; sus versiones perfectas se pueden alcanzar solo con el uso intensivo de la razón. Antes de nacer y olvidar todo, nuestras almas inmortales viven en el mundo de las formas, por lo que el proceso de adquirir conocimiento (creencias verdaderas con una justificación) es el proceso de recordar cómo realmente son las formas. En una sociedad ideal, cada individuo usa sus talentos naturales en su máximo potencial para cumplir el rol de una de tres clases: producción, defensa y gobierno. El alma también tiene tres partes análogas: deseo (busca sexo, dinero), espíritu (busca honor, fama) y racional (busca conocimiento). Las desiciones de los gobernantes tienen que estar basadas en la razón, por lo que los reyes tienen que ser filósofos (los mejores en intelecto y virtud, aristocracia).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Aristóteles&lt;/strong&gt; (384 aC, Grecia - todo en su justa medida): Saber algo es conocer todas sus causas, y cada objeto tiene cuatro: material (de qué está hecho), formal (cuál es su estructura), efectiva (qué lo creó o transformó al estado actual) y final (para qué sirve). De esto deriva que las cosas individuales no son copias de formas perfectas e inmutables, sino que la forma es una propiedad de la materia. Y cómo las cadenas casuales no pueden retroceder infinitamente, tiene que haber una primera causa que se causó a sí misma: esta causa es una mente llamada Dios. Solo con tener conocimientos no alcanza, también hay que llevarlos a la práctica por medio de hábitos virtuosos ("somos lo que hacemos repetidamente; la excelencia no es un acto es un hábito"), siendo que la virtud es lo que se encuentra en el punto medio entre un extremo por deficiencia y otro por exceso. Así como Sócrates dice que una vida no examinada no vale la pena ser vivida, Aristóteles agrega que una vida no planeada no vale la pena ser examinada: no se puede analizar algo si no hay un objetivo. Y si aún no se desarrollaron hábitos lo suficientemenre virtuosos como para identificar los objetivos adecuados, se deben imitar a quienes sí los poseen. El objetivo final de la vida es alcanzar la felicidad (o el bienestar, el florecimiento, etc de acuerdo a otras traducciones), y el camino para lograrlo varía de persona a persona por más que al final todos queremos lo mismo. Sin embargo, la verdadera felicidad es la que se obtiene cuando se vive de acuerdo a la causa final del ser humano: vivir a la altura de aquello que lo distingue, es decir, vivir de acuerdo a la razón. De todas formas, se debe tener en cuenta que la suerte juega el papel de facilitar o complicar el alcance a dicha felicidad y que la total suspensión del juicio no es posible. El mejor tipo de estado es el que proporciona a sus ciudadanos oportunidades para hacer ejercicio de sus intelectos (ocio) sin depender de objetos externos de estatus y bienes materiales.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Elije tu propio camino hacia la ataraxia - Escuelas de pensamiento&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Cinismo&lt;/strong&gt; (rechazo a las convenciones) - [Antístenes (445 aC, Grecia), Diógenes (412 aC, Grecia), Crates de Tebas (368 aC, Grecia)]: La forma de actuar debe ser dictada por las leyes de la virtud, ya sea que se adecuen o no a las leyes de la ciudad. Debemos independizarnos de todo tipo de convenciones y deseos para vivir la vida de un modo simple y natural.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Epicureísmo&lt;/strong&gt; (placer como ausencia de dolor) - [Epicuro (341 aC, Grecia)]: La naturaleza está compuesta de átomos indivisibles pero no mínimos: se componen de la unidad fundamental de materia (que no puede existir por sí misma). El mundo es completamente material, y las propiedades de las cosas que percibimos están causadas por las configuraciones de los átomos que las constituyen y por su interacción con los átomos de nuestros órganos sensoriales. Cuando morimos, la colección aleatoria de átomos que integran nuestro cuerpo se dispersa: "death is nothing to us; for that which has been dissolved into its elements experiences no sensations, and that which has no sensation is nothing to us." Esto significa que el proceso de morir puede provocar sufrimiento, pero el estado de muerte no porque ya se siente. El placer es el objetivo de la vida, pero definido en su forma más pura como la ausencia de dolor. Cuando deseamos algo es porque sentimos que nos falta algo, y eso es una forma de dolor. El estado de tranquilidad (ataraxia) es también un placer, y es el mejor tipo de placer: "ningún placer es malo por si mismo, pero las cosas que producen placer pueden acarrear problemas mucho más grandes que los propios placeres." &lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Estoicismo&lt;/strong&gt; (aceptar lo inevitable y enfrentar la adversidad) - [Zenón de Citio (334 aC, Chipre), Cleantes (331 aC, Turquía), Crisipo (281 aC, Turquía), Séneca (4 aC, Italia), Epicteto (55, Turquía), Marco Aurelio (121, Italia)]: El arjé es la materia, indestructible y eterna. Pero además hay otro principio fundamental: el logos (razón, destino, Dios) se extiende por todo el universo y lo organiza, haciéndolo pasar por un ciclo determinista e infinito de creación y destrucción. Esto significa que hay cuestiones que escapan necesariamente de nuestro control, pero la llave de la felicidad está en nuestras manos: se puede elegir ser indiferentes a lo inevitable y así lograr la libertad. Debemos gobernar racionalmente nuestros sentimientos mediante el autocontrol, porque son solo nuestras actitudes quienes hacen que la vida sea buena o mala. Lo mejor es mantener la calma en todo momento y ajustar nuestra visión del mundo para tener expectativas más realistas.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Escepticismo&lt;/strong&gt; (nada puede asegurarse) - [Pirrón de Elis (360 aC, Grecia), Timón (320 aC, Grecia), Arcesilao (315 aC, Grecia), Carnéades (214 aC, Libia)]: Siempre hay que suspender el juicio porque no existe un criterio de verdad capaz de asegurar algo completamente: las cosas tienen distintas apariencias para diferentes personas, momentos y condiciones, de modo que no se puede considerar que ninguna apareciencia represente definitivamente cómo es algo en realidad. No hay que tener creencias, no hay que estar comprometido, no hay que ser firme. La realidad es inestable e indeterminada, y son las convenciones y los hábitos lo que conforman las bases de todo lo que hace el ser humano. Las cosas que parecen malas no siempre son malas, porque la adversidad es lo que te prepara para afrontar los futuros problemas de la vida. Llevar el pensamiento escéptico a la práctica significa estar comprometido con la investigación y actuar de acuerdo a las creencias que parecen más razonables sin sostener que estas sean realmente ciertas.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Neoplatonismo&lt;/strong&gt; (fuente de tres niveles) - [Plotino (205, Egipto), Porfirio (233, Líbano), Jámblico (245, Siria), Proclo (412, Turquía)]: Hay una cadena jerárquica de existencia, que comienza con la causa definitiva del universo: el Uno, una mente única que está más allá de toda descripción. De el Uno surge el mundo de las formas, lugar donde residen nuestras almas (y por lo tanto, nuestra esencia). Al contemplar las formas, finalmente nuestras almas crean al mundo físico donde habita la materia. Somos almas atrapadas en un cuerpo que se encuentra en un mundo inferior, por lo que el mal surge a partir de concentrarnos en cosas que se encuentran por debajo de la cadena de existencia (es decir, en cosas materiales). El propósito de una vida virtuosa es regresar a la unidad con el Uno, y la mejor forma de lograrlo es a través de la contemplación filosófica y el rechazo hacia las tentaciones materiales.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;</content><category term="Filosofía"></category></entry><entry><title>Ancient philosophy</title><link href="https://facuroffet99.github.io/en/notes/philosophy_1.html" rel="alternate"></link><published>2025-05-21T11:35:00-03:00</published><updated>2025-05-21T11:35:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-05-21:/en/notes/philosophy_1.html</id><summary type="html">&lt;p&gt;Personal notes on ancient philosophy: the pre-Socratics, Socrates, Plato, Aristotle, and the Stoic, Epicurean, Cynic, Skeptic, and Neoplatonist schools. Based on A.C. Grayling and the Philosophize This! podcast.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Ancient philosophy&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;These are my personal notes from Part 1 of the book &lt;a href="https://www.google.com.ar/books/edition/The_History_of_Philosophy/tkvRvQEACAAJ?hl=es-419"&gt;The History of Philosophy&lt;/a&gt; by A.C. Grayling, and from episodes 1 to 6 and 10 to 15 of the podcast &lt;a href="https://open.spotify.com/show/2Shpxw7dPoxRJCdfFXTWLE"&gt;Philosophize This!&lt;/a&gt; by Stephen West.&lt;/p&gt;
&lt;p&gt;I introduce each philosopher using the format &lt;em&gt;Name (Year, Place – Description)&lt;/em&gt;. Year refers to the year of birth (or an approximation, as some dates are uncertain), and Place refers to the current country of their city of birth. In the Description, I highlight either what I consider the philosopher’s main contribution or a memorable trait that helps me recall them easily.&lt;/p&gt;
&lt;p&gt;Sometimes it's more helpful to group philosophers by schools of thought rather than detailing their individual contributions. In such cases, the format is &lt;em&gt;School – Description [Name1 (Year1, Place1), Name2 (Year2, Place2), ...]&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Philosophers before philosophy – The presocratics&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Thales of Miletus&lt;/strong&gt; (624 BCE, Turkey – the beginning): First to use rational explanations that excluded the gods. The &lt;em&gt;archê&lt;/em&gt; (the fundamental substance of all things) is water. The soul is the cause of motion.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Anaximander&lt;/strong&gt; (610 BCE, Turkey – first non-material reality): The &lt;em&gt;archê&lt;/em&gt; is not a material substance, but the infinite. The infinite is the universal source of creation and destruction, and it restores natural laws when they are disrupted.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Anaximenes&lt;/strong&gt; (590 BCE, Turkey – first systematic theory): The &lt;em&gt;archê&lt;/em&gt; is air, which gives shape to things by rarefying ("expanding") or condensing ("compressing").&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pythagoras&lt;/strong&gt; (570 BCE, Greece – a cult of mathematics and music): Everything can be understood through numbers. The purpose of life is to end the cycle of suffering and reincarnation in order to live freely and eternally in a blessed realm. Humans are partly evil, and the only way to purify oneself is to live a life of restraint and contemplation through mathematics, music, and astronomy. Understanding these three fields means understanding the eternal laws of the universe, and living in harmony with them is the closest we can get to immortality. Reaching conclusions through reason is superior to relying on the senses.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Xenophanes&lt;/strong&gt; (560 BCE, Turkey – religion as projection of human flaws): Rejected traditional religion and its anthropomorphic Olympian gods. Natural phenomena must be investigated and understood. Humans attribute to gods all the traits we’re ashamed of to feel better about ourselves. First to say that God is everything.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Heraclitus&lt;/strong&gt; (535 BCE, Turkey – the enigmatic): There is a cosmic law (&lt;em&gt;logos&lt;/em&gt;) that governs everything. All is in a state of constant change: "you can’t step into the same river twice." The &lt;em&gt;archê&lt;/em&gt; is fire.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Parmenides&lt;/strong&gt; (530 BCE, Italy – what is, is; and what is not, is not): Nothing can come from nothing, so change is impossible. The universe is an eternal whole—there is no empty space and all change is an illusion. Only what can be thought exists; the real is the same as the thinkable.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Anaxagoras&lt;/strong&gt; (500 BCE, Turkey – infinite elements): There are infinitely many fundamental elements ("seeds"), all present in everything; individual things differ only by the predominance (not absence) of some elements over others. The organizing principle of the universe is an immaterial, intelligent force that provides causal power ("power over") to the elements.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Empedocles&lt;/strong&gt; (495 BCE, Italy – a god among mortals): The &lt;em&gt;archê&lt;/em&gt; consists of four eternal and immutable elements (air, fire, water, and earth), which combine in different proportions to form the world we see. Two fundamental forces—Love and Strife—are in cyclical conflict, creating change by uniting or separating the elements.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Zeno of Elea&lt;/strong&gt; (490 BCE, Italy – Achilles and the tortoise): Movement is an illusion—you cannot cross an infinite number of points in a finite amount of time. Appearance is not necessarily reality.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Democritus&lt;/strong&gt; (460 BCE, Greece – atomism): Everything is made of atoms (tiny, indivisible particles) and empty space. Atoms themselves do not change, but their configurations do, generating infinite instances of a single reality. The universe is deterministic: given the initial conditions of an atom and enough computational power, one could predict its entire future.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;The Sophists&lt;/strong&gt; (masters of oratory and rhetoric) – [Protagoras (485 BCE, Greece), Gorgias (480 BCE, Italy), Prodicus (465 BCE, Greece), Hippias (443 BCE, Greece), Antiphon (480 BCE, Greece), Critias (460 BCE, Greece)]: Every argument has two sides, and neither is inherently more valid than the other. People can be persuaded to any extreme through rhetoric. It is the person holding a belief who gives it value—not the belief itself or the facts behind it: "man is the measure of all things." What is true or right for one person may not be for another—everything is subjective.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;The holy trinity – Socrates, Plato and Aristotle&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Socrates&lt;/strong&gt; (470 BCE, Greece – method of refutation): Brought philosophy to the public by encouraging people to question their beliefs and guiding them toward truth: "Well, now that you know you don’t know what you’re talking about, we can start making progress." Philosophy is discussion, questioning, and argumentation. The only way to live a virtuous life is to know the true definitions of virtuous words—and reason is the only way to discover them. The pursuit of knowledge is life’s ultimate goal and the highest virtue; an unexamined life is not worth living.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Plato&lt;/strong&gt; (427 BCE, Greece – world of forms): Concepts like justice and beauty are not defined by perception, but are eternal, perfect, and immutable. The same is true for all physical objects. These perfect versions do not exist in our sensory world but in a separate realm of Forms. What we perceive are imperfect, ever-changing copies; only reason allows access to the true Forms. Before birth, our immortal souls reside in the world of Forms, and learning is the process of remembering them. In an ideal society, each person uses their natural talents to fulfill the role of one of three classes: producers, defenders, and rulers. The soul also has three parts: desire (seeks sex, money), spirit (seeks honor, fame), and reason (seeks knowledge). Rulers' decisions must be based on reason, so philosophers—those most virtuous and intelligent—should rule (aristocracy).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Aristotle&lt;/strong&gt; (384 BCE, Greece – everything in due measure): To know something is to understand all its causes, which are four: material (what it’s made of), formal (its structure), efficient (what created or changed it), and final (its purpose). Individual things are not imperfect copies of immutable Forms; rather, form is a property of matter. Since causal chains cannot regress infinitely, there must be a first cause that causes itself: this is a mind called God. Knowledge alone is not enough; it must be put into practice through virtuous habits: "we are what we repeatedly do; excellence, then, is not an act but a habit." Virtue lies in the mean between deficiency and excess. Just as Socrates said an unexamined life is not worth living, Aristotle adds that an unplanned life is not worth examining—you can’t analyze without a goal. If one hasn’t yet developed virtuous habits to identify worthy goals, one should imitate those who have. The ultimate goal of life is to achieve happiness (or flourishing, well-being, etc., depending on the translation), and while the path may differ from person to person, we all ultimately seek the same thing. True happiness is achieved by living according to the final cause of human beings: to live in accordance with reason, which is what makes us human. Still, one must consider that luck plays a role in enabling or hindering the pursuit of happiness, and total suspension of judgment is not possible. The best state is one that provides its citizens with opportunities to exercise their intellect (leisure) without relying on material wealth or status symbols.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Choose your own path to ataraxia – Schools of thought&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Cynicism&lt;/strong&gt; (rejection of conventions) – [Antisthenes (445 BCE, Greece), Diogenes (412 BCE, Greece), Crates of Thebes (368 BCE, Greece)]: Actions should follow the laws of virtue, regardless of whether they align with the city’s laws. We must free ourselves from conventions and desires to live a simple and natural life.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Epicureanism&lt;/strong&gt; (pleasure as absence of pain) – [Epicurus (341 BCE, Greece)]: Nature is made of indivisible atoms, but not minimal ones—they are composed of a fundamental unit of matter (which cannot exist by itself). The world is entirely material, and the properties of things we perceive result from atomic configurations and their interaction with our sensory organs. When we die, the random collection of atoms that make us up disperses: "death is nothing to us; for that which has been dissolved into its elements experiences no sensations, and that which has no sensation is nothing to us." Dying may be painful, but death itself cannot be, since there is no perception. The goal of life is pleasure—defined in its purest form as the absence of pain. When we desire something, it’s because we feel a lack—that lack is a form of pain. The state of tranquility (&lt;em&gt;ataraxia&lt;/em&gt;) is also a form of pleasure, and the highest kind: "no pleasure is bad in itself, but the things that produce pleasure can lead to much greater problems than the pleasures themselves."&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Stoicism&lt;/strong&gt; (accept the inevitable and face adversity) – [Zeno of Citium (334 BCE, Cyprus), Cleanthes (331 BCE, Turkey), Chrysippus (281 BCE, Turkey), Seneca (4 BCE, Italy), Epictetus (55, Turkey), Marcus Aurelius (121, Italy)]: The &lt;em&gt;archê&lt;/em&gt; is matter, indestructible and eternal. But there’s another fundamental principle: &lt;em&gt;logos&lt;/em&gt; (reason, fate, God) pervades the universe, organizing it in a deterministic, infinite cycle of creation and destruction. Some things are necessarily beyond our control, but happiness is within reach: we can choose to be indifferent to the inevitable and thus be free. We must rationally govern our emotions through self-control, since it is our attitudes that make life good or bad. The best path is to remain calm at all times and adjust our worldview to develop more realistic expectations.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Skepticism&lt;/strong&gt; (nothing can be assured) – [Pyrrho of Elis (360 BCE, Greece), Timon (320 BCE, Greece), Arcesilaus (315 BCE, Greece), Carneades (214 BCE, Libya)]: One must always suspend judgment because there is no criterion of truth capable of guaranteeing anything completely: things appear differently to different people, times, and conditions, so no appearance can definitively represent how something truly is. One should not hold beliefs, should not be committed, and should not be firm. Reality is unstable and indeterminate, and it is conventions and habits that form the basis of all human behavior. Things that seem bad are not always bad, because adversity is what prepares us to face future challenges in life. Putting skeptical thought into practice means being committed to inquiry and acting according to the beliefs that seem most reasonable—without claiming that they are actually true.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Neoplatonism&lt;/strong&gt; (three-level fountain) – [Plotinus (205, Egypt), Porphyry (233, Lebanon), Iamblichus (245, Syria), Proclus (412, Turkey)]: There is a hierarchical chain of existence that begins with the ultimate cause of the universe: the One, a unique mind that is beyond all description. From the One arises the world of Forms, the place where our souls dwell (and thus, our essence). By contemplating the Forms, our souls eventually create the physical world, where matter resides. We are souls trapped in a body located in a lower world, so evil arises from focusing on things that lie beneath the chain of existence—that is, material things. The purpose of a virtuous life is to return to unity with the One, and the best way to achieve this is through philosophical contemplation and rejecting material temptations.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;</content><category term="Philosophy"></category></entry><entry><title>Tiempo y clima</title><link href="https://facuroffet99.github.io/notes/weather_and_climate.html" rel="alternate"></link><published>2025-05-15T15:16:00-03:00</published><updated>2025-05-15T15:16:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-05-15:/notes/weather_and_climate.html</id><summary type="html">&lt;p&gt;Notas personales sobre tiempo y clima: tipos de nubes, fenómenos atmosféricos y conceptos fundamentales de meteorología y climatología. Basadas en el curso de Mel Strong en YouTube.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Tiempo y clima&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;Estas son mis notas personales del curso &lt;a href="https://www.youtube.com/playlist?list=PLCewapt2D7PsD6fL3KkNInBYCQHLZuGoM"&gt;Introduction to weather and climate short course&lt;/a&gt; de Mel Strong. &lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Tipos de nubes&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;El sistema tradicional de clasificación de nubes tiene en cuenta tanto alturas como formas. La forma pueden ser cumuloform ("puffy", con posible desarrollo mayoritario tanto vertical como horizontal), stratoform ("big solid gray sky", una capa uniforme) o cirroform ("wispy", de formas muy variadas). La altura pueden ser alta (cirro-), media (alto-) o baja (-).&lt;/li&gt;
&lt;li&gt;Cumulus (Cu): suelen tener bases planas.&lt;/li&gt;
&lt;li&gt;Altocumulus (Ac): se ven más chicas por la altura pero también lo son, suelen formar patrones de parches (o a veces en filas), tienen sombras (se ven tridimensionales).&lt;/li&gt;
&lt;li&gt;Cirrocumulus (Cc): muy pequeñas y finas, se puede ver a través de ellas, tienen pocas sombras (se ven bidimensionales).&lt;/li&gt;
&lt;li&gt;Cumulonimbus (Cb): inicia como un cumulus y se desarrolla verticalmente (ocupa todas las capas de altura), único tipo de cumuloform capaz de precipitar, único tipo de nube capaz de un "yunque" de hielo en su parte superior (su presencia casi garantiza precipitación), su lluvia presenta un límite bien marcado.&lt;/li&gt;
&lt;li&gt;Stratocumulus (Sc): gran conjunto de cumulus que se tocan (o casi) entre sí, el tipo de nube más común en el mundo (pero ocurre mayormente sobre los océanos).&lt;/li&gt;
&lt;li&gt;Stratus (St): cielo gris donde no se ve el sol, puede tener un poco de textura.&lt;/li&gt;
&lt;li&gt;Altostratus (As): se ve donde está el sol pero aparece como una bola difusa.&lt;/li&gt;
&lt;li&gt;Cirrostratus (Cs): están hechas de hielo y casi no se ven, producen anillos alrededor del sol (que suelen tener colores de arcoíris).&lt;/li&gt;
&lt;li&gt;Nimbostratus (Ns): stratus que produce precipitación, no se ven los límites de la lluvia.&lt;/li&gt;
&lt;li&gt;Cirrus (Ci): están hechas solo de hielo, presentan una gran variedad de texturas (plumas, pelos, telarañas, densas, ganchos, líneas) pero siempre se distinguen sus bordes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Algunos subtipos interesantes del sistema tradicional&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Lenticular: forma de disco, suelen crearse sobre picos de montaña, suelen estar fijas en un lugar.&lt;/li&gt;
&lt;li&gt;Mammatus: aire frío que se hunde en la base de los cumulonimbus.&lt;/li&gt;
&lt;li&gt;Niebla: stratus sobre la superficie terrestre.&lt;/li&gt;
&lt;li&gt;Noctilente: el tipo de nube que se forma a mayor altura (aprox 85km), solo existen cerca de los polos, solo se pueden ver tras el atarceder cuando son iluminadas por rayos que no llegan a la superficie terrestre.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Humedad&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;El 99.9% de la atmósfera está compuesto por 78% N₂, 21% O₂ y 1% Ar (composición seca). El agua no se toma en cuenta para esos cálculos porque es un gas variable: puede representar entre el 0% y el 4% de los gases en el aire.&lt;/li&gt;
&lt;li&gt;La humedad se puede medir como un ratio de mezcla (gramos de vapor de agua en un kilo de aire).&lt;/li&gt;
&lt;li&gt;El aire tiene un límite acerca de cuánto vapor de agua puede contener (el aire se satura de agua). Ese límite de ratio de mezcla depende de la temperatura en una forma exponencial, lo cual implica que el aire frío es siempre seco mientras que el caliente tiene la capacidad de ser húmedo (aunque pueda no serlo).&lt;/li&gt;
&lt;li&gt;Cuando la temperatura baja, llega un punto en el que el aire no puede contener más agua, por lo que empieza a condensar (o helar si es debajo de 0º). Esta temperatura se llama punto de rocío: el aire es seco cuando es baja y húmedo cuando es alta.&lt;/li&gt;
&lt;li&gt;Agregar agua al aire incrementa tanto el ratio de mezcla como el punto de rocío (tengo que bajar menos la temperatura para saturar el aire si es más húmedo). El inverso también se cumple.&lt;/li&gt;
&lt;li&gt;La humedad también se puede medir de forma relativa: es el ratio de mezcla actual dividido el máximo posible (a una dada temperatura). Es proporcional a la cantidad de agua e inversamente proporcional a la temperatura.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Evaporación&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Siempre que un cuerpo de agua está expuesto a la atmósfera, hay un constante flujo de moléculas. La temperatura controla el ratio con el que se van del líquido (más temperatura implica más evaporación), mientras que la humedad relativa controla en ratio con el que entran (más % de humedad implica más condensación).&lt;/li&gt;
&lt;li&gt;La transición de líquido a gas absorbe energía térmica, por lo que la evaporación del sudor enfría al cuerpo. Si hay mucha humedad en el aire, el sudor no se evapora.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Formación de nubes&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;El principio de formación de una nube es el mismo que el del rocío, pero en vez de formarse condensación en una superficie sucede en particulas microscópicas (0.0002mm) que se encuentran en la atmosfera. Pueden ser polvo de roca, ceniza, sal, polen, bacterias, etc.&lt;/li&gt;
&lt;li&gt;Las gotitas de agua que se encuentran en las nubes son microscópicas (0.02mm-0.05mm), mientras que las gotas de lluvia son considerablemente más grandes (2mm).&lt;/li&gt;
&lt;li&gt;El aire que sube se expande y se enfría, el aire que baja se comprime y se calienta. Esto sucede a un ratio de 9.8ºC/km cuando la humedad es menor al 100% o de 3.6-5.5ºC/km (depende de la temperatura) cuando la humedad es del 100% (asumiendo en ambos casos ausencia de intercambio de energía con el entorno). La tasa de enfriamiento es menor cuando el aire está saturado porque la condensación libera calor latente, contrarrestando parcialmente el enfriamiento por expansión.&lt;/li&gt;
&lt;li&gt;Cuando un "grupo" de aire cerca de la superficie está a una mayor temperatura que el resto de la atmósfera, comienza a subir. Continúa subiendo hasta que las temperaturas se igualan y luego baja, formando una celda de convección (terma). Si antes de que las temperaturas se igualen se llega al punto de rocío, se forma una nube. &lt;/li&gt;
&lt;li&gt;El proceso de convección explicado arriba es solo uno de las cuatro mecanismos principales de ascenso del aire y formación de nubes. Los otros son ascenso orográfico (ver "Circulación") , convergencia (ver "Circulación") y ascenso frontal (ver "Frentes").&lt;/li&gt;
&lt;li&gt;Una nube va a ser más alta mientras más caliente el aire en la superficie (el que sube) y mientras más frío el aire en la altura (el de la atmósfera).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Formación de precipitación&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;En la parte superior de una cumuloninbus hay hielo. Un poco más abajo, el hielo convive con agua en estado supercongelado (gotas microscópicas debajo de 0ºC). De acuerdo al proceso de Bergeron, el agua supercongelada se une al hielo, lo cuál incrementa el tamaño de los cristales y los convierte en copos de nieve. Estos copos caen pero antes suelen derretirse cuando llegan a la parte inferior (líquida) de la nube, produciendo lluvia. Nota: este proceso es distinto en zonas tropicales debido a la altísima humedad, por lo que la lluvia en esa zona puede originarse como gotas de agua directamente.&lt;/li&gt;
&lt;li&gt;Aparte del aire caliente que sube en una nube (updraft), cuando hay precipitación también hay aire frío que baja (downdraft). El downdraft puede tomar una velocidad considerable (microburst), chocando a 110km/h con la superficie y generando un frente de salida (outflow) que se propaga hacia los costados (puede cruzar estados). Este proceso también ocurre si la lluvia se evapora antes de llegar a la superficie, formando una especie de tentáculos (virga).&lt;/li&gt;
&lt;li&gt;No está muy en claro cómo se forma el granizo, pero se cree que se produce cuando el updraft mantiene a los copos de nieve dando vueltas por más tiempo en la nube, permitiendo que crezcan mucho más.&lt;/li&gt;
&lt;li&gt;Por motivos no super entendidos, hay zonas en las nubes donde se acumulan carga negativas (suelen estar más abajo) y otras donde se acumulan cargas positivas (suelen estar más arriba). Cuando la carga acumulada llega a cierto punto, se empieza a emitir gas ionizado que se mueve de manera aleatoria (como una escalera). Como la base negativa de la nube induce una carga positiva en un entorno de la superficie terrestre, el gas ionizado positivo proveniente de la Tierra puede entrar en contacto con el ionizado negativo de la nube y producir un rayo. También puede suceder que los iones positivos vengan de la misma nube o de otra, produciendo rayos intranube o internube.&lt;/li&gt;
&lt;li&gt;Cuando se produce un rayo, el aire que atraviesa se calienta a miles de grados y se expande. Luego, como se produjo un vacío, la presión atmosférica colapsa el aire de manera violenta, produciendo un trueno.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Presión y viento&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;La presión atmosférica no se siente porque las moléculas de aire ejercen la misma fuerza en todas las direcciones, por lo que se cancelan. Lo que sí se puede sentir es un desbalance de presiones.&lt;/li&gt;
&lt;li&gt;Hay un límite en la altura en la que se puede subir un líquido por un tubo al hacer succión: una vez que se extrae todo el aire, la presión atmosférica mantiene fijo el nivel (la fuerza que ejerce sobre la superficie del líquido hace que este suba por el tubo).&lt;/li&gt;
&lt;li&gt;Cuando los vientos en la tropopausa convergen y chocan, generan una columna de aire que desciende (no pueden ir más arriba de la tropopausa, es una barrera), produciendo un incremento (H) en la presión atmosférica en la superficie . En el caso de que los vientos diverjan, el proceso inverso tiene efecto y disminuye (L) la presión superficial. Tanto H como L no son procesos localizados: suelen abarcan varios países.&lt;/li&gt;
&lt;li&gt;En el ecuador hay una banda L (sobre todo en los océanos) debido a que la superficie es tan cálida y húmeda que el aire permanentemente tiende a subir. Hay una enorme cantidad de cumulonimbus.&lt;/li&gt;
&lt;li&gt;Los cambios de presión debido a la elevación del terreno son mucho mayores que los producidos por el clima, por lo que no se reporta la presión real sino una ajustada por altura (a nivel del mar). De esta forma, en todos los lugares del mundo la presión promedio es 1013hPa.&lt;/li&gt;
&lt;li&gt;El movimiento inicial del aire se debe a la Fuerza del Gradiente de Presión (FGP), que empuja el aire desde H hacia L. Sin embargo, la rotación de la Tierra introduce la Fuerza de Coriolis, que desvía este movimiento hacia la derecha en el Hemisferio Norte y hacia la izquierda en el Hemisferio Sur.&lt;/li&gt;
&lt;li&gt;En la tropopausa, la FGP y Coriolis tienden a equilibrarse y el viento resultante fluye paralelo a las líneas isobáricas. Cerca de la superficie, la fricción con el terreno frena el viento, permitiendo que el viento cruce las isobaras ligeramente. La velocidad de los vientos aumenta con la intensidad del gradiente de presión.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Tropósfera y estratósfera&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;La temperatura de la atmósfera disminuye a medida que se incrementa la altura hasta llegar a la tropopausa (aprox 11km), límite entre tropósfera y estratósfera. Del otro lado, la temperatura aumenta con la altura porque el ozono presente absorbe radiación ultravioleta del sol y libera calor.&lt;/li&gt;
&lt;li&gt;Los clorofluorocarburos que se liberaban a la atmósfera impeden la regeneración de las moléculas de ozono, aumentando considerablemente el famoso agujero de la capa de ozono. Tras varios tratados internacionales que comenzaron en 1987, el daño comenzó a recuperarse lentamente tras un mínimo en 2006. Los CFCs dejaron de usarse totalmente en 2015.&lt;/li&gt;
&lt;li&gt;Todas las nubes, el 99% de la humedad y el 75% de todo el aire de la atmósfera se encuentra en la tropósfera. En las demás capas el cielo se ve negro.&lt;/li&gt;
&lt;li&gt;Los gases cuyas moléculas son más pesadas suelen concentrarse más cerca de la superficie terrestre que las livianas (aunque todas son afectadas por la gravedad). De todas formas, las moléculas poseen energía cinética suficiente como para rebotar entre ellas y mantenarse en la atmósfera.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Frentes&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;A nivel superficial la temperatura del aire varía aproximadamente con un gradiente que va del ecuador hacia los polos, aunque la temperatura sobre los continentes fluctúa mucho más que sobre los océanos (distinta capacidad térmica).&lt;/li&gt;
&lt;li&gt;A ~3km de altura la cuestión es distinta: la temperatura es bastante homogénea en una banda ancha en torno al ecuador, pero hay un marcado contraste llegando hacia los polos. El límite entre el aire caliente y el frío se llama frente polar, y su forma varía día a día.&lt;/li&gt;
&lt;li&gt;Cuando en un frente polar el aire caliente invade al aire frío, se forma un frente cálido: el aire caliente empuja al frío con una forma de rampa lenta de poca inclinación. Si un frente cálido viene hacia vos, vas a experimentar (en orden): cirrus, cirrostratus, altostratus, stratus, nimbostratus.&lt;/li&gt;
&lt;li&gt;El caso contrario (frío invade caliente) se llama frente frío: el aire frío empuja al caliente con una forma de rampa rápida de inclinación pronunciada. Si un frente frío viene hacia vos, es probable que experimentes cumulonimbus de manera repentina.&lt;/li&gt;
&lt;li&gt;Cuando tanto aire frío como aire caliente quieren invadirse a la vez, se forma un frente estacionario. Sus consecuencias son una mezcla de las de los frentes cálidos y fríos.&lt;/li&gt;
&lt;li&gt;Cuando un frente frío alcanza desde atrás a un frente cálido que va en la misma dirección (porque va más rápido), se forma un frente ocluído.&lt;/li&gt;
&lt;li&gt;Debido a la rotación de la Tierra, los frentes estacionarios que se forman en el frente polar comiezan a girar. Esto da inicio a un frente frío y a uno cálido que rotan en el mismo sentido (en torno a L), hasta que el primero alcanza al segundo y se ocluyen. Esto es lo que se llama un ciclón extratropical.&lt;/li&gt;
&lt;li&gt;Los ciclones tropicales (huracanes) poseen un mecanismo de formación distinto, que está relacionado con la alta tasa de evaporación de los océanos cálidos. No ocurren exactamente en la banda del ecuador (se necesita la rotación producida por el efecto Coriolis) pero sí a latitudes bajas.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Circulación&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;La rotación de la Tierra hace que los vientos del este converjan cerca del ecuador, en la zona llamada ITCZ (intertropical convergence zone). Cuando convergen, estos suben debido a las altas temperaturas y forman una banda de enormes cumulonimbus (y de baja presión como se dijo más arriba). &lt;/li&gt;
&lt;li&gt;La ITCZ coincide con la banda de más alta temperatura y no se encuentra exactamente en el ecuador.&lt;/li&gt;
&lt;li&gt;Cuando el viento que sube en la ITCZ llega a la tropopausa, se dispersa hacia el norte y el sur hasta volver a caer alrededor de 30ºN y 30ºS de latitud, formando ahora dos bandas de alta presión. No son perfectas por la diferencia continente/océano, así que más bandas terminan siendo zonas más puntuales llamadas altas subtropicales.&lt;/li&gt;
&lt;li&gt;También hay bandas de presión baja a 60ºN y 60ºS, y puntos de presión alta en los polos. En total existen tres tipos de celdas (de menor latitud a mayor): Hadley (la de efectos más fuertes), Ferrel y Polar.&lt;/li&gt;
&lt;li&gt;Una tormenta que viene desde el oceáno se intensifica cuando llega a un continente porque recibe un boost de aire cálido. Si hay una montaña, la tormenta se incrementa todavía más al subir. Cuando baja del otro lado de la montaña, el proceso inverso ocurre pero no de forma simétrica debido a que el agua perdida como precipitación no se recupera (ya no tiene una fuente de humedad debajo). Este efecto conocido como sombra orográfica hace que las montañas tengan un lado seco y uno húmedo.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Cambios de estaciones&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;El tiempo se refiere a las condiciones atmosféricas actuales, que son predecibles hasta no más de 5 días (es un sistema caótico). El clima se refiere a las condiciones promedio en un determinado lugar, y es predecible hasta décadas en adelante.&lt;/li&gt;
&lt;li&gt;Las estaciones no se deben a la distancia de la Tierra al sol, sino a la inclinación de la órbita terrestre.&lt;/li&gt;
&lt;li&gt;Los cambios de estaciones hacen que la ITCZ y las demás bandas L y H se desplacen a lo largo del año.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Monzones&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Debido a la distinta capacidad térmica entre continentes y océanos, se produce un reverso estacional en la dirección de los vientos, que a su vez puede implicar la existencia de una estación seca y una húmeda. Este proceso se llama monzón, y es más notorio en India y el sudeste asíatico porque la ITCZ pasa por arriba de esa zona.&lt;/li&gt;
&lt;li&gt;En invierno, el aire más cálido sobre los océanos sube y es reemplazado por el viento frío y seco proveniente de las montañas. En verano, el aire caliente continental es el que sube, dándole lugar al viento húmedo proveniente del oceáno.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;El Niño y la Niña (ENSO)&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Los vientos producidos por los altos subtropicales hacen que las aguas frías de los polos se desplacen hacia el ecuador en las costas este, y que las aguas cálidas del ecuador se desplacen hacia los polos en las costas oeste. En el lado este, el agua desplazada en la superficie es reemplazada por agua más fría proveniente del fondo del océano, produciendo condiciones idóneas para la proliferación de peces.&lt;/li&gt;
&lt;li&gt;En el sur del océano Pacífico hay veces en que los vientos de su alto subtropical se debilitan (o incluso cambia de H a L y los vientos cambian de sentido), por lo que las costas oeste de sudamérica se calientan y los peces se alejan del continente. Este proceso se conoce como el Niño.&lt;/li&gt;
&lt;li&gt;El proceso contrario también puede ocurrir: los vientos de los altos subtropicales se incrementan y el agua de la costa oeste sudamericana se vuelve más fría. Este fenómeno es la Niña.&lt;/li&gt;
&lt;li&gt;Tanto el Niño y la Niña son eventos naturales no predecibles y suelen durar varios meses (~4 a 8). Solamente ocurren en el océano Pacífico porque es el único lo suficientemente grande para que sus efectos se noten, pero igual son capaces de afectar el clima de forma global (más que nada los niveles de precipitación).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Efecto invernadero&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;La mayor parte de la radiación del sol que llega a la superficie terrestre es de onda corta (incluye hasta infrarojo cercano). La tierra absorbe una gran parte y emite radiación de onda larga (calor) hacia el espacio como respuesta.&lt;/li&gt;
&lt;li&gt;Tanto el O₂ como el N₂ son transparentes antes ambos tipos de radiaciones. En cambio, los gases de efecto invernadero (H₂O, CO₂, CH₄) son excitables cuando reciben radiación de onda larga, por lo que absorben una parte de ella y luego la emiten hacia una dirección aleatoria. Este proceso es el efecto invernadero y es necesario para hacer posible la vida en la Tierra.&lt;/li&gt;
&lt;li&gt;Si bien el agua no absorbe radiación de onda corta, las nubes son capaces de difractarla y reflejarla. Esto reduce la energía que llega hasta la superficie y ayuda a disminuir la temperatura. Pero como el agua también es un gas de efecto invernadero, cuando está nublado no solo se obtienen días frescos sino también noches cálidas.&lt;/li&gt;
&lt;li&gt;En los últimos 100 años, los humanos hemos emitido una cantidad sin precedentes de gases de efecto invernadero a la atmósfera, provocando un aumento gradual en la temperatura global promedio.&lt;/li&gt;
&lt;li&gt;Si bien el agua es el gas de efecto invernadero más abundante en la atmósfera, su cantidad no puede aumentar desproporcionadamente porque termina precipitando en el corto plazo. Esto no sucede con los otros gases, que permanecen en la atmósfera por muchos años.&lt;/li&gt;
&lt;li&gt;En USA, el 82.2% de la contribución al efecto invernadero es producida solo por emisiones de CO₂. De ese porcentaje, la amplia mayoría (más del 90%) proviene de combustibles fósiles, que a su vez de subdivide en: 38% generación de energía, 34% transporte, 16% industria, 7% residencial y 5% comercial. Otro 10% de la contribución es producida por emisiones de CH₄, que se debe en mayor medida a la ganadería, la extracción de gas natural y los vertederos. Y el 5.1% restante es producida por emisiones de N₂O, debida de manera desproporcionada a la fertilización de suelo agrícola. (Ver las gráficas de &lt;a href="https://www.epa.gov/ghgemissions/global-greenhouse-gas-overview"&gt;EPA&lt;/a&gt; para valores globales).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Ciclo del carbono&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Reservas de carbono y flujos netos: &lt;ul&gt;
&lt;li&gt;Vegetación: 600 Tg (+2,6 Tg/año)&lt;/li&gt;
&lt;li&gt;Atmósfera: 829 Tg (+4 Tg/año)&lt;/li&gt;
&lt;li&gt;Océano: 38.000 Tg (+2,3 Tg/año)&lt;/li&gt;
&lt;li&gt;Suelo: 2.000 Tg&lt;/li&gt;
&lt;li&gt;Combustibles fósiles: 4.100 Tg&lt;/li&gt;
&lt;li&gt;Rocas carbonatadas: 80.000.000 Tg&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Agregar CO₂ a los océanos genera ácido carbónico, lo cual afecta a los corales y a toda la biodiversidad que depende de ellos.&lt;/li&gt;
&lt;li&gt;La curva de Keeling muestra que la evolución del CO₂ en la atmósfera a lo largo del tiempo tiene dos componentes. Una es una oscilación natural que se repite todos los años (debido a la diferencia entre cantidad de vegetación entre hemisferios: valle cuando es verano en el norte y pico cuando es invierno), y la otra es un incremento cuasi lineal causado por las emisiones humanas de los últimos 150 años.&lt;/li&gt;
&lt;/ul&gt;</content><category term="Ciencias de la Tierra"></category></entry><entry><title>Weather and climate</title><link href="https://facuroffet99.github.io/en/notes/weather_and_climate.html" rel="alternate"></link><published>2025-05-15T15:16:00-03:00</published><updated>2025-05-15T15:16:00-03:00</updated><author><name>Facundo Roffet</name></author><id>tag:facuroffet99.github.io,2025-05-15:/en/notes/weather_and_climate.html</id><summary type="html">&lt;p&gt;Personal notes on weather and climate: cloud types, atmospheric phenomena, and fundamental concepts in meteorology and climatology. Based on Mel Strong's YouTube course.&lt;/p&gt;</summary><content type="html">&lt;!-- Hide default title --&gt;
&lt;style&gt; h1.entry-title, h1.post-title, h1.title, h1:first-of-type {display: none;} &lt;/style&gt;
&lt;!-- Add custom title --&gt;
&lt;h2 style="text-align: center; font-size: 3em; color: rgba(12, 205, 76, 0.927);"&gt;Weather and climate&lt;/h2&gt;

&lt;!----------------------------------------------------------------------------&gt;

&lt;blockquote&gt;
&lt;p&gt;These are my personal notes from the &lt;a href="https://www.youtube.com/playlist?list=PLCewapt2D7PsD6fL3KkNInBYCQHLZuGoM"&gt;Introduction to weather and climate short course&lt;/a&gt; by Mel Strong.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;!----------------------------------------------------------------------------&gt;

&lt;h2&gt;Cloud Types&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;The traditional cloud classification system considers both altitude and shape. Shape can be cumuliform (“puffy,” with significant vertical and horizontal development), stratiform (“big solid gray sky,” a uniform layer), or cirriform (“wispy,” with very varied forms). Altitude can be high (cirro-), middle (alto-), or low (-).&lt;/li&gt;
&lt;li&gt;Cumulus (Cu): usually have flat bases.&lt;/li&gt;
&lt;li&gt;Altocumulus (Ac): appear smaller due to altitude and actually are smaller; often form patchy patterns (or sometimes in rows); cast shadows and look three-dimensional.&lt;/li&gt;
&lt;li&gt;Cirrocumulus (Cc): very small and thin; you can see through them; have few shadows and appear two-dimensional.&lt;/li&gt;
&lt;li&gt;Cumulonimbus (Cb): start as cumulus and then grow vertically through all altitude layers; the only cumuliform cloud that produces precipitation and the only cloud capable of forming an ice “anvil” at its top (its presence almost guarantees precipitation); rainfall has a sharply defined edge.&lt;/li&gt;
&lt;li&gt;Stratocumulus (Sc): large clusters of cumulus clouds touching (or nearly touching) one another; the most common cloud type worldwide (but mainly over the oceans).&lt;/li&gt;
&lt;li&gt;Stratus (St): gray sky with the sun obscured; may have a little texture.&lt;/li&gt;
&lt;li&gt;Altostratus (As): you can see the sun through them but it appears as a diffuse disk.&lt;/li&gt;
&lt;li&gt;Cirrostratus (Cs): made of ice and almost invisible; produce halos around the sun (often with rainbow colors).&lt;/li&gt;
&lt;li&gt;Nimbostratus (Ns): stratus clouds that produce precipitation; the rain boundaries are indistinct.&lt;/li&gt;
&lt;li&gt;Cirrus (Ci): composed entirely of ice; exhibit a wide variety of textures (feathery, hairlike, cobweb, dense, hooked, streaky) but always have sharply defined edges.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Some Interesting Subtypes in the Traditional System&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Lenticular: disc-shaped, typically form over mountain peaks, usually stationary.&lt;/li&gt;
&lt;li&gt;Mammatus: pouch-like formations hanging from the base of cumulonimbus clouds, caused by sinking cold air.&lt;/li&gt;
&lt;li&gt;Fog: stratus cloud at the Earth’s surface.&lt;/li&gt;
&lt;li&gt;Noctilucent: the highest-forming clouds (around 85 km altitude), found only near the poles, visible after sunset when illuminated by sunlight that doesn’t reach the surface.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Humidity&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Dry air (99.9% of the atmosphere) is composed of 78% N₂, 21% O₂, and 1% Ar. Water vapor isn’t included in those figures because it’s variable: it can range from 0% to 4% of the air’s composition.&lt;/li&gt;
&lt;li&gt;Humidity can be measured as a mixing ratio (grams of water vapor per kilogram of air).&lt;/li&gt;
&lt;li&gt;Air has an upper limit on how much water vapor it can hold (saturation). That limit on the mixing ratio depends exponentially on temperature, which means cold air is always dry and warm air has the capacity to be humid (though it might not be).&lt;/li&gt;
&lt;li&gt;When temperature drops, the air reaches a point where it can’t hold more water, and condensation (or freezing below 0 °C) begins. This temperature is called the dew point: low dew points indicate dry air, high dew points indicate humid air.&lt;/li&gt;
&lt;li&gt;Adding water vapor to air increases both the mixing ratio and the dew point (i.e., the air must be cooled less to reach saturation when it's more humid). The reverse also holds.&lt;/li&gt;
&lt;li&gt;Humidity can also be measured as relative humidity: the current mixing ratio divided by the maximum possible at a given temperature. It’s proportional to the amount of water and inversely proportional to temperature.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Evaporation&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Whenever a body of water is exposed to the atmosphere, molecules constantly exchange between liquid and gas. Temperature controls the rate at which molecules leave the liquid (higher temperature → more evaporation), while relative humidity controls the rate at which they return (higher % humidity → more condensation).&lt;/li&gt;
&lt;li&gt;The liquid-to-gas transition absorbs thermal energy, which is why sweating cools the body. If the air is very humid, sweat won’t evaporate.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Cloud Formation&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;The principle of cloud formation is the same as dew formation, but instead of condensing on a surface, water vapor condenses on microscopic particles (about 0.0002 mm) in the atmosphere, such as rock dust, ash, salt, pollen, bacteria, etc.&lt;/li&gt;
&lt;li&gt;Cloud droplets are microscopic (0.02–0.05 mm), whereas raindrops are much larger (about 2 mm).&lt;/li&gt;
&lt;li&gt;Rising air expands and cools, while sinking air compresses and warms. This occurs at about 9.8 °C/km when humidity is below 100%, or 3.6–5.5 °C/km (depending on temperature) when humidity is at 100%, assuming no heat exchange with the environment. The cooling rate is lower in saturated air because condensation releases latent heat, partially offsetting adiabatic cooling.&lt;/li&gt;
&lt;li&gt;When a parcel of air near the surface is warmer than its surroundings, it rises until its temperature equals that of the environment and then sinks, forming a convection cell (thermal). If it reaches its dew point before temperatures equalize, a cloud forms.&lt;/li&gt;
&lt;li&gt;Convection is only one of the four main uplift mechanisms for cloud formation. The others are orographic uplift (see “Circulation”), convergence (see “Circulation”), and frontal uplift (see “Fronts”).&lt;/li&gt;
&lt;li&gt;A cloud will be higher if surface air is warmer (the rising parcel) and upper-level air is colder (the surrounding atmosphere).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Precipitation Formation&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;At the top of a cumulonimbus cloud there’s ice. Slightly below, ice coexists with supercooled water droplets (microscopic droplets below 0 °C). Through the Bergeron process, supercooled droplets join ice crystals, growing flakes that eventually fall. They often melt in the cloud’s lower (liquid) region, producing rain. Note: in tropical regions with very high humidity, rainfall may form as water droplets directly.&lt;/li&gt;
&lt;li&gt;Besides the warm updraft in a cloud, precipitation also generates a cold downdraft. Downdrafts can reach high speeds (microbursts), striking the surface at up to 110 km/h and creating an outflow boundary that spreads sideways (sometimes across states). Virga occurs when rain evaporates before reaching the ground, leaving streaky “tentacles.”&lt;/li&gt;
&lt;li&gt;Hail formation isn’t fully understood but is thought to occur when strong updrafts keep hailstones suspended longer, allowing them to grow larger.&lt;/li&gt;
&lt;li&gt;For not-fully-understood reasons, negative charges accumulate in some cloud regions (usually lower) and positive charges in others (usually higher). When charge separation reaches a threshold, ionized gas is emitted in random paths (like a ladder). The negatively charged cloud base induces a positive charge on the ground, and when positive ions from Earth meet negative ions from the cloud, a lightning bolt forms. Lightning can also occur within a single cloud or between clouds.&lt;/li&gt;
&lt;li&gt;A lightning stroke heats the air to thousands of degrees, causing rapid expansion. When that heated air cools, the sudden collapse produces thunder.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Pressure and Wind&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;We don’t feel atmospheric pressure because molecules push equally in all directions, canceling out net force. We do feel pressure imbalances.&lt;/li&gt;
&lt;li&gt;There’s a limit to how high you can draw liquid up a tube by suction: once the air is removed, atmospheric pressure on the liquid’s surface pushes it up the tube.&lt;/li&gt;
&lt;li&gt;When winds converge aloft at the tropopause, they force air downward (they can’t go above the tropopause), creating a surface high (H). When winds diverge aloft, they cause a surface low (L). These high- and low-pressure areas cover large regions, often spanning multiple countries.&lt;/li&gt;
&lt;li&gt;Near the equator there’s a persistent low (especially over oceans) because warm, humid surface air continually rises, generating abundant cumulonimbus development.&lt;/li&gt;
&lt;li&gt;Terrain elevation causes much larger pressure changes than weather does, so reported pressures are adjusted to sea level. This ensures a global average of about 1013 hPa everywhere.&lt;/li&gt;
&lt;li&gt;Air initially moves from high to low pressure due to the Pressure Gradient Force (PGF). Earth’s rotation introduces the Coriolis Force, deflecting winds to the right in the Northern Hemisphere and to the left in the Southern Hemisphere.&lt;/li&gt;
&lt;li&gt;At the tropopause, PGF and Coriolis nearly balance, so winds flow parallel to isobars. Near the surface, friction slows winds, allowing them to cross isobars toward lower pressure. Wind speed increases with the pressure gradient’s strength.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Troposphere and Stratosphere&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Air temperature decreases with height up to the tropopause (around 11 km), the boundary between the troposphere and stratosphere. Above that, temperature increases with altitude because ozone absorbs ultraviolet radiation and releases heat.&lt;/li&gt;
&lt;li&gt;Chlorofluorocarbons once released into the atmosphere hinder ozone regeneration, enlarging the ozone hole. Following international agreements starting in 1987, damage bottomed out in 2006 and has been slowly recovering. CFCs were completely phased out by 2015.&lt;/li&gt;
&lt;li&gt;All clouds, 99% of atmospheric humidity, and 75% of the atmosphere’s mass are in the troposphere. Above it, the sky appears black.&lt;/li&gt;
&lt;li&gt;Heavier gas molecules tend to concentrate near the surface more than lighter ones (though gravity acts on all molecules). Nevertheless, molecular collisions keep gases well mixed.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Fronts&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Near the surface, air temperature generally decreases from the equator toward the poles, though continental temperatures vary more than oceanic ones (different heat capacities).&lt;/li&gt;
&lt;li&gt;Around 3 km altitude, temperatures are fairly uniform in a broad equatorial band, but contrast sharply toward the poles. The boundary between warm and cold air is the polar front, and its position shifts daily.&lt;/li&gt;
&lt;li&gt;When warm air advances into cold air along a polar front, a warm front forms: warm air slides up over cold with a gentle slope. As a warm front approaches you, you’ll see (in order): cirrus, cirrostratus, altostratus, stratus, nimbostratus.&lt;/li&gt;
&lt;li&gt;Conversely, when cold air pushes into warm air, a cold front forms: cold air undercuts warm with a steep slope. As a cold front approaches, you’re likely to see sudden cumulonimbus development.&lt;/li&gt;
&lt;li&gt;When neither air mass displaces the other, a stationary front forms, producing mixed effects of both warm and cold fronts.&lt;/li&gt;
&lt;li&gt;When a cold front overtakes a warm front moving in the same direction (because it’s faster), an occluded front forms.&lt;/li&gt;
&lt;li&gt;Due to Earth’s rotation, stationary fronts along the polar front begin to rotate, spawning both a warm and a cold front that circle around a low (L) until the cold front catches the warm one and occlusion occurs. This system is called an extratropical cyclone.&lt;/li&gt;
&lt;li&gt;Tropical cyclones (hurricanes) form by a different mechanism, linked to high evaporation over warm oceans. They don’t form right at the equator (Coriolis effect) but at low latitudes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Circulation&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Earth’s rotation causes easterly trade winds to converge near the equator in the Intertropical Convergence Zone (ITCZ). As they converge, air rises due to high surface temperatures, forming a band of large cumulonimbus clouds and low pressure.&lt;/li&gt;
&lt;li&gt;The ITCZ aligns with the hottest surface band and isn’t exactly at the equator.&lt;/li&gt;
&lt;li&gt;Rising air in the ITCZ reaches the tropopause, then spreads north and south before sinking around 30° N and 30° S, creating two subtropical high-pressure belts. Because continents and oceans differ, these highs appear as more localized subtropical highs.&lt;/li&gt;
&lt;li&gt;There are also low-pressure belts near 60° N and 60° S, and high-pressure centers at the poles. In total, three circulation cells exist (from low to high latitude): Hadley (strongest effects), Ferrel, and Polar.&lt;/li&gt;
&lt;li&gt;A storm moving from ocean to land intensifies as it draws warmth; over mountains it intensifies further. On descending the lee side, the reverse happens but not symmetrically because precipitation depletes moisture (no replenishing water source). This “rain shadow” effect creates a dry side and a wet side of mountains.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Seasonal Changes&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Weather refers to current atmospheric conditions, predictable up to about five days (chaotic system). Climate refers to average conditions at a location, predictable for decades.&lt;/li&gt;
&lt;li&gt;Seasons are caused by Earth’s axial tilt, not changes in distance from the Sun.&lt;/li&gt;
&lt;li&gt;Seasonal changes shift the ITCZ and other low- and high-pressure belts throughout the year.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Monsoons&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Different heat capacities of land and ocean cause a seasonal reversal of wind direction, bringing distinct wet and dry seasons. This process is called a monsoon and is most pronounced in India and Southeast Asia, where the ITCZ passes overhead.&lt;/li&gt;
&lt;li&gt;In winter, warmer ocean air rises and is replaced by cold, dry mountain air. In summer, hot continental air rises, drawing in moist ocean air.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;El Niño and La Niña (ENSO)&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Subtropical high-pressure winds carry cold polar waters toward the equator along eastern ocean boundaries, while warm equatorial waters move toward the poles along western boundaries. On eastern coasts, upwelling of cold deep water supports abundant fisheries.&lt;/li&gt;
&lt;li&gt;In the southern Pacific Ocean, subtropical highs sometimes weaken (or reverse to lows), allowing warm coastal waters to spread along South America—this is El Niño.&lt;/li&gt;
&lt;li&gt;The opposite can also occur: stronger subtropical highs bring colder coastal waters along western South America—this is La Niña.&lt;/li&gt;
&lt;li&gt;Both El Niño and La Niña are natural, unpredictable events lasting several months (\~4–8). They occur only in the Pacific Ocean (large enough to feel effects) but can impact global precipitation patterns.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Greenhouse Effect&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Most solar radiation reaching Earth’s surface is shortwave (up to near-infrared). The ground absorbs much of it and emits longwave (heat) radiation back to space.&lt;/li&gt;
&lt;li&gt;O₂ and N₂ are transparent to both shortwave and longwave. Greenhouse gases (H₂O, CO₂, CH₄) absorb longwave radiation and re-emit it in random directions. This greenhouse effect is essential for life on Earth.&lt;/li&gt;
&lt;li&gt;Water vapor doesn’t absorb shortwave, but clouds scatter and reflect it, reducing surface heating. Since water vapor is also a greenhouse gas, cloudy days are cooler but nights are warmer.&lt;/li&gt;
&lt;li&gt;Over the last 100 years, human emissions of greenhouse gases have risen unprecedentedly, gradually increasing global average temperatures.&lt;/li&gt;
&lt;li&gt;Although water vapor is the most abundant greenhouse gas, its atmospheric concentration can’t increase indefinitely because it precipitates quickly. Other greenhouse gases remain in the atmosphere for years.&lt;/li&gt;
&lt;li&gt;In the USA, 82.2% of greenhouse-effect contribution comes from CO₂ emissions. Over 90% of that CO₂ comes from fossil fuels, subdivided into: 38% energy generation, 34% transportation, 16% industry, 7% residential, and 5% commercial. Another 10% comes from CH₄ emissions (mainly agriculture, natural gas extraction, and landfills). The remaining 5.1% is from N₂O emissions, disproportionately from agricultural soil fertilization. (See the &lt;a href="https://www.epa.gov/ghgemissions/global-greenhouse-gas-overview"&gt;EPA’s graphs&lt;/a&gt; for global figures.)&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Carbon Cycle&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Carbon reservoirs and net fluxes:&lt;/li&gt;
&lt;li&gt;Vegetation: 600 Tg (+2.6 Tg/yr)&lt;/li&gt;
&lt;li&gt;Atmosphere: 829 Tg (+4 Tg/yr)&lt;/li&gt;
&lt;li&gt;Ocean: 38,000 Tg (+2.3 Tg/yr)&lt;/li&gt;
&lt;li&gt;Soil: 2,000 Tg&lt;/li&gt;
&lt;li&gt;Fossil fuels: 4,100 Tg&lt;/li&gt;
&lt;li&gt;Carbonate rocks: 80,000,000 Tg&lt;/li&gt;
&lt;li&gt;Adding CO₂ to the oceans forms carbonic acid, which harms corals and their dependent biodiversity.&lt;/li&gt;
&lt;li&gt;The Keeling Curve shows atmospheric CO₂ over time has two components: a seasonal oscillation (due to differing vegetation cycles between hemispheres: trough in northern summer, peak in northern winter) and a quasi-linear rise from human emissions over the last 150 years.&lt;/li&gt;
&lt;/ul&gt;</content><category term="Earth sciences"></category></entry></feed>