From d7794a901eb9df8725d4409f2b3a6dd1305b6a63 Mon Sep 17 00:00:00 2001 From: ANGEL MERINO Date: Tue, 26 Aug 2025 00:35:05 -0500 Subject: [PATCH 1/4] Update 03_word_embeddings_solutions.ipynb --- solutions/03_word_embeddings_solutions.ipynb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solutions/03_word_embeddings_solutions.ipynb b/solutions/03_word_embeddings_solutions.ipynb index bf0c725..aa9814a 100644 --- a/solutions/03_word_embeddings_solutions.ipynb +++ b/solutions/03_word_embeddings_solutions.ipynb @@ -368,11 +368,11 @@ "id": "0f0142b3-545b-4f52-8e7b-2711e20abbd6", "metadata": {}, "source": [ - "## 🥊 Challenge 3: Construct a Semantic Axis\n", + "## 🥊 Desafío 3: Construir un Eje Semántico\n", "\n", - "Now it's your turn! We have two sets of pole words for \"female\" and \"male\". These are example words tested in Bolukbasi et al., 2016. We will get the embeddings for these words from glove to calculate the gender axis. \n", + "¡Ahora te toca! Tenemos dos conjuntos de palabras clave para \"female\" y \"male\". Estos son ejemplos de palabras probadas en Bolukbasi et al., 2016. Obtendremos las incrustaciones de estas palabras de glove para calcular el eje de género.\n", "\n", - "The cell for the function `get_semaxis` provides some starting code. Complete the function. If everything runs, the embedding size of the semantic axis should be the same as the size of the input vector. " + "La celda de la función `get_semaxis` proporciona código inicial. Completa la función. Si todo se ejecuta, el tamaño de la incrustación del eje semántico debería ser igual al tamaño del vector de entrada." ] }, { From 7219f92887d1c7dbb1c56089061cd80946ab42fd Mon Sep 17 00:00:00 2001 From: rebe1603 Date: Tue, 26 Aug 2025 09:52:41 -0500 Subject: [PATCH 2/4] =?UTF-8?q?Traduccion=20en=20espa=C3=B1ol=20de=20word?= =?UTF-8?q?=20embeddings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lessons/03_word_embeddings.ipynb | 334 +++++++++++++++---------------- 1 file changed, 162 insertions(+), 172 deletions(-) diff --git a/lessons/03_word_embeddings.ipynb b/lessons/03_word_embeddings.ipynb index 2bbb64e..b8930bd 100644 --- a/lessons/03_word_embeddings.ipynb +++ b/lessons/03_word_embeddings.ipynb @@ -5,28 +5,27 @@ "id": "2c0c2f15-1a64-4b2b-8ca1-270f05aa24b9", "metadata": {}, "source": [ - "# Python Text Analysis: Word Embeddings\n", - "\n", + "# Análisis de texto en Python: incrustaciones de palabras\n", "
\n", " \n", - "### Learning Objectives \n", + "### Objetivos de aprendizaje\n", "\n", - "* Recognize differences between bag-of-words representations and word embeddings.\n", - "* Learn how word embeddings capture the meaning of words.\n", - "* Calculate cosine similarity to capture linguistic concepts.\n", - "* Understand that word embeddings models can be biased, and develop approaches to uncover these biases.\n", + "* Reconocer las diferencias entre las representaciones de bolsas de palabras y las incrustaciones de palabras.\n", + "* Aprender cómo las incrustaciones de palabras capturan el significado de las palabras.\n", + "* Calcular la similitud del coseno para capturar conceptos lingüísticos.\n", + "* Comprender que los modelos de incrustaciones de palabras pueden estar sesgados y desarrollar enfoques para detectar estos sesgos.\n", "
\n", "\n", - "### Icons Used in This Notebook\n", - "🔔 **Question**: A quick question to help you understand what's going on.
\n", - "🥊 **Challenge**: Interactive excersise. We'll work through these in the workshop!
\n", - "🎬 **Demo**: Showing off something more advanced – so you know what Python can be used for!
\n", + "### Íconos usados ​​en este cuaderno\n", + "🔔 **Pregunta**: Una pregunta rápida para ayudarte a entender qué sucede.
\n", + "🥊 **Desafío**: Ejercicios interactivos. ¡Los trabajaremos en el taller!
\n", + "🎬 **Demostración**: Mostrando algo más avanzado para que sepas para qué se puede usar Python.
\n", "\n", - "### Sections\n", - "1. [Understand Word Embeddings](#section1)\n", - "2. [Word Similarity](#section2)\n", - "3. [Word Analogy](#section3)\n", - "4. [Bias in Word Embeddings](#section4)" + "### Secciones\n", + "1. [Comprender las incrustaciones de palabras](#section1)\n", + "2. [Similitud de palabras](#section2)\n", + "3. [Analogía de palabras](#section3)\n", + "4. [Sesgo en las incrustaciones de palabras](#section4)" ] }, { @@ -46,41 +45,39 @@ "id": "94fc6996", "metadata": {}, "source": [ - "In Part 2, we have tried converting the text data to a numerical representation with a Bags of Words (BoW) representation and beyond that, Term Frequency-Inverse Document Frequeny (TF-IDF). These methods make heavy use of word frequency but not much of the relative position between words, but there's still rich semantic meanings and syntactic relations left to be captured beyond independent word frequency. \n", - "\n", - "We need a more powerful tool that has the potential to represent rich semantics (and more) of our text data. In the final part of this series, we will dive into word embeddings, a method widely combined with more advanced Natural Language Processing (NLP) tasks. We'll make extensive use of the `gensim` package, which hosts a range of word embedding models, including `word2vec` and `GloVe`, the two models we'll explore today.\n", + "En la Parte 2, intentamos convertir los datos de texto a una representación numérica mediante una representación de Bolsas de Palabras (BoW) y, además, mediante la Frecuencia de Términos-Frecuencia Inversa de Documentos (TF-IDF). Estos métodos hacen un uso intensivo de la frecuencia de las palabras, pero no de la posición relativa entre ellas. Sin embargo, aún quedan por capturar significados semánticos y relaciones sintácticas de gran valor más allá de la frecuencia de palabras independientes.\n", "\n", + "Necesitamos una herramienta más potente que tenga el potencial de representar la semántica de gran valor (y más) de nuestros datos de texto. En la parte final de esta serie, profundizaremos en las incrustaciones de palabras, un método que se combina ampliamente con tareas más avanzadas de Procesamiento del Lenguaje Natural (PLN). Haremos un uso extensivo del paquete `gensim`, que alberga diversos modelos de incrustación de palabras, incluyendo `word2vec` y `GloVe`, los dos modelos que exploraremos hoy.\n", "\n", "\n", - "# Understand Word Emebeddings \n", - "\n", - "As famously put by British Linguist J.R. Firth:\n", + "# Comprender las incrustaciones de palabras\n", "\n", - "> **You shall know a word by the company it keeps.**\n", + "Como dijo el lingüista británico J.R. Firth:\n", "\n", - "This quote sums it all for the essence of word embeddings, which take the numerical representation of text further to the next step. \n", + "> **Reconocerás una palabra por la compañía que tiene.**\n", "\n", - "Recall from Part 2 that a BoW representation is a **sparse** matrix. Its dimension is determined by vocabulary size and the number of documents. Importantly, a sparse matrix like BoW is interpretable; the cell values refer to the count of a word in a document. Oftentimes the cell values are zero: many words simply don't appear in a document at all. \n", + "Esta cita resume la esencia de las incrustaciones de palabras, que llevan la representación numérica del texto a un nivel superior.\n", "\n", - "We can think of word embedding as a matrix likewise, but this time a **dense** matrix, where the cell values are real numbers. Word embeddings project a word's meaning onto a high-dimensional vector space—that's why it is also called **word vectors**. A word vector is essentially an array of real numbers, the length of which, as we'll see today, could be as low as 50, or as high as 300 (or even higher in Large Language Models). These real numbers do not make explicit sense to us, but this is not to say they are *meaningless*. It is now believed that a word's meaning can be captured by the vector representation, which we will return to shortly. \n", + "Recuerde de la Parte 2 que una representación BoW es una matriz **dispersa**. Su dimensión está determinada por el tamaño del vocabulario y el número de documentos. Es importante destacar que una matriz dispersa como BoW es interpretable; los valores de celda se refieren al número de palabras en un documento. A menudo, los valores de celda son cero: muchas palabras simplemente no aparecen en un documento.\n", "\n", + "También podemos pensar en las incrustaciones de palabras como una matriz, pero esta vez como una matriz **densa**, donde los valores de celda son números reales. Las incrustaciones de palabras proyectan el significado de una palabra en un espacio vectorial de alta dimensión; por eso también se denominan **vectores de palabras**. Un vector de palabras es esencialmente un array de números reales, cuya longitud, como veremos hoy, puede ser tan pequeña como 50 o tan grande como 300 (o incluso mayor en Modelos de Lenguaje Grandes). Estos números reales no tienen sentido explícito para nosotros, pero esto no significa que carezcan de significado. Actualmente se cree que el significado de una palabra puede ser capturado por la representación vectorial, que abordaremos en breve.\n", "BOW:\n", - "- Sparse matrix\n", - "- Dimension: $D$ x $V$, where rows are **D**ocuments and columns are words in the **V**ocabulary.\n", - "- Interpretable: e.g., \"bank\" and \"banker\" may appear in a financial document, but probably not \"bane.\"\n", - " \n", + "- Matriz dispersa\n", + "- Dimensión: $D$ x $V$, donde las filas son **D** documentos y las columnas son palabras del **V**ocabulario.\n", + "- Interpretable: p. ej., \"banco\" y \"banquero\" pueden aparecer en un documento financiero, pero probablemente no \"bane\".\n", + "\n", "\"BoW\"\n", "\n", - "Word embeddings:\n", - "- Dense matrix\n", - "- Dimension: $V$ x $D$, where rows are **V**ocabulary and columns are vectors with dimension **D**.\n", - "- Not immediately interpretable\n", + "Incrustaciones de palabras:\n", + "- Matriz densa\n", + "- Dimensión: $V$ x $D$, donde las filas son **V**ocabulario y las columnas son vectores de dimensión **D**.\n", + "- No interpretable inmediatamente\n", "\n", "\"BoW\"\n", "\n", - "Today, we are going to explore two widely used word embedding models, `word2vec` and `GloVe`. We will use the package `gensim` to access both models, so let's install gensim first.\n", + "Hoy exploraremos dos modelos de incrustación de palabras ampliamente utilizados: `word2vec` y `GloVe`. Usaremos el paquete `gensim` para acceder a ambos modelos, así que primero instalemos gensim.\n", "\n", - "## Install `gensim`" + "## Instalar `gensim`" ] }, { @@ -101,9 +98,9 @@ "id": "1756207c-98a2-4310-a153-55f07b2c280d", "metadata": {}, "source": [ - "The word embedding models hosted in `gensim` can be retrieved in two ways. We can download them using the `gensim.downloader` API. Alternatively, these models can be downloaded to your local machine ahead of time, and then we use `KeyedVectors` to load them in. \n", + "Los modelos de incrustación de palabras alojados en `gensim` se pueden obtener de dos maneras. Podemos descargarlos mediante la API `gensim.downloader`. Como alternativa, estos modelos se pueden descargar previamente a su equipo local y luego usar `KeyedVectors` para cargarlos.\n", "\n", - "For the two models we will be working with today, we recommend downloading `word2vec` to your computer first. You can retrieve it via [this link](https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?resourcekey=0-wjGZdNAUop6WykTtMip30g). For `GloVe`, a smaller model, we can use the gensim API directly when we reach that section. " + "Para los dos modelos con los que trabajaremos hoy, recomendamos descargar primero `word2vec` a su equipo. Puede obtenerlo a través de [este enlace](https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?resourcekey=0-wjGZdNAUop6WykTtMip30g). Para `GloVe`, un modelo más pequeño, podemos usar la API de gensim directamente al llegar a esa sección." ] }, { @@ -125,35 +122,34 @@ "source": [ "## `word2vec`\n", "\n", - "The idea of word vectors, i.e, projecting a word's meaning onto a vector space, has been around for a long time. The `word2vec` model, proposed by [Mikolov et al.](https://arxiv.org/abs/1301.3781) in 2013, introduces an efficient model of word embeddings, since then it has stimulated a new wave of research on this topic. \n", + "La idea de los vectores de palabras, es decir, la proyección del significado de una palabra en un espacio vectorial, existe desde hace mucho tiempo. El modelo «word2vec», propuesto por [Mikolov et al.](https://arxiv.org/abs/1301.3781) en 2013, introduce un modelo eficiente de incrustaciones de palabras y, desde entonces, ha impulsado una nueva ola de investigación sobre este tema.\n", "\n", - "The key question asked in this paper is: how do we go about learning a good vector representation from the data?\n", + "La pregunta clave de este artículo es: ¿cómo podemos obtener una buena representación vectorial a partir de los datos?\n", "\n", - "Mikolov et al. proposed two approaches: the **continuous bag-of-words (CBOW)** and the **skip-gram (SG)**. They are similar in that we use the vector representation of a token to try and predict what the nearby tokens are with a shallow neural network. \n", + "Mikolov et al. propusieron dos enfoques: la **bolsa continua de palabras (CBOW)** y el **grama de saltos (SG)**. Son similares, ya que utilizamos la representación vectorial de un token para intentar predecir cuáles son los tokens cercanos con una red neuronal superficial.\n", "\n", - "Take the following sentence from Merriam-Webster for example. If our target token is $w_t$, \"banks,\" the context tokens would be the preceding tokens $w_{t-2}, w_{t-1}$ and the following ones $w_{t+1}, w_{t+2}$. This example corresponds to a **window size** of 2: 2 words on either side of the target word. Similarly when we move onto the next tagret token, the context window moves as well.\n", + "Tomemos como ejemplo la siguiente frase de Merriam-Webster. Si nuestro token objetivo es $w_t$, \"bancos\", los tokens de contexto serían los tokens anteriores $w_{t-2}, w_{t-1}$ y los siguientes $w_{t+1}, w_{t+2}$. Este ejemplo corresponde a un **tamaño de ventana** de 2: 2 palabras a cada lado de la palabra objetivo. De forma similar, al pasar al siguiente token objetivo, la ventana de contexto también se mueve.\n", "\n", "\"Trget\n", "\n", - "In the continuous bag-of-words model, our goal is to predict the target token, given the context tokens. In the skip-gram model, the goal is to predict the context tokens from the target token. This is the reverse of the continuous bag-of-words and is a harder task, since we have to predict more from less information.\n", - "\n", + "En el modelo de bolsa de palabras continua, nuestro objetivo es predecir el token objetivo, dados los tokens de contexto. En el modelo de salto de gramática, el objetivo es predecir los tokens de contexto a partir del token objetivo. Esto es lo contrario del modelo de bolsa de palabras continua y es una tarea más compleja, ya que tenemos que predecir más a partir de menos información.\n", "\"word2vec\"\n", "\n", - "**CBOW** (Left):\n", - "- **Input**: context tokens\n", - "- **Inner dimension**: embedding layer\n", - "- **Output**: the target token\n", + "**CBOW** (Izquierda):\n", + "- **Entrada**: tokens de contexto\n", + "- **Dimensión interna**: capa de incrustación\n", + "- **Salida**: el token objetivo\n", "\n", - "**Skip-gram** (Right):\n", - "- **Input**: the target token\n", - "- **Inner dimension**: embedding layer\n", - "- **Output**: context tokens\n", + "**Skip-gram** (Derecha):\n", + "- **Entrada**: el token objetivo\n", + "- **Dimensión interna**: capa de incrustación\n", + "- **Salida**: tokens de contexto\n", "\n", - "The above figure illustrates the direction of prediction. It also serves as a schematic representation of a neural network, i.e., the mechanism underlying the training of `word2vec`. The input and output are known to us, represented by **one-hot encodings** in Mikolov et al. The **hidden layer**, the inner dimension between the input and the output, is the vector representation that the model is trying to learn. \n", + "La figura anterior ilustra la dirección de la predicción. También sirve como representación esquemática de una red neuronal, es decir, el mecanismo subyacente al entrenamiento de `word2vec`. Conocemos la entrada y la salida, representadas por **codificaciones one-hot** en Mikolov et al. La **capa oculta**, la dimensión interna entre la entrada y la salida, es la representación vectorial que el modelo intenta aprender.\n", "\n", - "Here, we provide a brief explanation of where embedding come from, but we won't go into the specifics of training a neural network. The `word2vec` model we will be interacting with today is **pretrained**, meaning that the embeddings have already been trained on a large corpus (or a number of corpora). Pretrained `word2vec` and `GloVe`, as well as other models, are available through `gensim`. \n", + "Aquí, ofrecemos una breve explicación del origen de la incrustación, pero no profundizaremos en los detalles del entrenamiento de una red neuronal. El modelo `word2vec` con el que interactuaremos hoy está **preentrenado**, lo que significa que las incrustaciones ya se han entrenado en un corpus grande (o varios corpus). `word2vec` y `GloVe` preentrenados, así como otros modelos, están disponibles a través de `gensim`.\n", "\n", - "Let's take a look at the list of models that `gensim` provides:" + "Echemos un vistazo a la lista de modelos que ofrece `gensim`:" ] }, { @@ -195,13 +191,13 @@ "id": "c508421b-dd32-4173-8716-b47f89cd1a51", "metadata": {}, "source": [ - "These models are named following the **model-corpora-dimension** fashion. The one called `word2vec-google-news-300` is what we are looking for! This is a `word2vec` model that is trained on Google News; the dimension of word embedding is 300. \n", + "Estos modelos se nombran según la fórmula **modelo-corpus-dimensión**. El modelo `word2vec-google-news-300` es el que buscamos. Se trata de un modelo `word2vec` entrenado en Google Noticias; la dimensión de inserción de palabras es 300.\n", "\n", - "As mentioned previously, we can retrieve this model in two ways:\n", - "- Download it via `api.load()`\n", - "- Download the model as a zip file and then load it in with `KeyedVectors.load()`\n", + "Como se mencionó anteriormente, podemos obtener este modelo de dos maneras:\n", + "- Descargarlo mediante `api.load()`\n", + "- Descargar el modelo como archivo zip y luego cargarlo con `KeyedVectors.load()`\n", "\n", - "The pretrained word2vec is archived by Google. You can download it via [this Google Drive link](https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?resourcekey=0-wjGZdNAUop6WykTtMip30g). " + "Google archiva el modelo `word2vec` preentrenado. Puede descargarlo mediante [este enlace de Google Drive](https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?resourcekey=0-wjGZdNAUop6WykTtMip30g)." ] }, { @@ -222,7 +218,7 @@ "id": "d40b0380-54bf-47ba-aded-55e7b52c19d3", "metadata": {}, "source": [ - "The argument `binary` asks whether the model is in the binary format. If you place the downloaded model in the `data` folder, the following file path should work." + "El argumento `binario` pregunta si el modelo está en formato binario. Si coloca el modelo descargado en la carpeta `data`, la siguiente ruta de archivo debería funcionar." ] }, { @@ -241,11 +237,11 @@ "id": "925db1ea-6295-47b7-b6f2-45941c993e5c", "metadata": {}, "source": [ - "Ta-da! Our pretrained `word2vec` is ready to use!\n", + "¡Listo! ¡Nuestro `word2vec` preentrenado está listo para usar!\n", "\n", - "Accessing the actual word vectors can be done by treating the word vector model as a dictionary. \n", + "Se puede acceder a los vectores de palabras reales tratando el modelo de vectores de palabras como un diccionario.\n", "\n", - "For example, let's take a look at the word vector for \"banana.\"" + "Por ejemplo, veamos el vector de palabras para \"banana\"." ] }, { @@ -351,7 +347,7 @@ "id": "4bf15e57-7c49-4238-849b-90cc30813d2e", "metadata": {}, "source": [ - "Let's inspect the shape of the \"banana\" vector. " + "Inspeccionemos la forma del vector \"banana\"." ] }, { @@ -380,11 +376,11 @@ "id": "5d1de233-cef4-48c8-9f5d-57107a16d02d", "metadata": {}, "source": [ - "As promised, it is an 1-D array that holds 300 values. \n", + "Como se prometió, es una matriz unidimensional que contiene 300 valores.\n", "\n", - "These values appear to be random floats and don't really make sense to us at the moment, but they are numerical representations on which we can perform computations. \n", + "Estos valores parecen ser números de punto flotante aleatorios y no tienen mucho sentido en este momento, pero son representaciones numéricas con las que podemos realizar cálculos.\n", "\n", - "Let's take a look at a few examples!" + "¡Veamos algunos ejemplos!" ] }, { @@ -394,15 +390,15 @@ "source": [ "\n", "\n", - "# Word Similarity\n", + "# Similitud de Palabras\n", "\n", - "The first question we can ask is: what words are similar to \"bank\"? In vector space, we expect similar words to have vectors that are close to each other.\n", + "La primera pregunta que podemos hacernos es: ¿qué palabras son similares a \"banco\"? En el espacio vectorial, esperamos que las palabras similares tengan vectores cercanos entre sí.\n", "\n", - "There are many metrics for measuring vector similarity; one of the most widely used is [**cosine similarity**](https://en.wikipedia.org/wiki/Cosine_similarity). Orthogonal vectors have a cosine similarity of 0, and parallel vectors have a cosine similarity of 1.\n", + "Existen muchas métricas para medir la similitud de vectores; una de las más utilizadas es la [**similitud de coseno**](https://en.wikipedia.org/wiki/Cosine_similarity). Los vectores ortogonales tienen una similitud de coseno de 0, y los vectores paralelos tienen una similitud de coseno de 1.\n", "\n", - "`gensim` provides a function called `most_similar` that lets us find the words most similar to a queried word. The output is a tuple containing candidate words and their cosine similarities to the queried word.\n", + "`gensim` proporciona una función llamada `most_similar` que nos permite encontrar las palabras más similares a la palabra consultada. El resultado es una tupla con las palabras candidatas y sus similitudes de coseno con la palabra consultada.\n", "\n", - "Let's give it a shot!" + "¡Intentémoslo!" ] }, { @@ -440,13 +436,13 @@ "id": "133dd9f2-115e-4b75-9379-4f465e117b97", "metadata": {}, "source": [ - "It looks like words that are most similar to \"bank\" are other financial terms! \n", + "Parece que las palabras más similares a \"banco\" son otros términos financieros.\n", "\n", - "Recall that `word2vec` is trained to capture a word's meaning based on contextual information. These words are considered similar to \"bank\" because they appear in similar contexts. \n", + "Recuerde que `word2vec` está entrenado para capturar el significado de una palabra basándose en información contextual. Estas palabras se consideran similares a \"banco\" porque aparecen en contextos similares.\n", "\n", - "In addition to querying for the most similar words, we can also ask the model to return the cosine similarity between two words by calling the function `similarity`.\n", + "Además de consultar las palabras más similares, también podemos pedirle al modelo que devuelva la similitud de coseno entre dos palabras llamando a la función `similarity`.\n", "\n", - "Let's go ahead and check out the similarities between the following four pairs of words. In each pair, we have \"river\" and \"bank,\" but the form of \"bank\" varies. Let's see if word forms make a difference!" + "Analicemos las similitudes entre los siguientes cuatro pares de palabras. En cada par, tenemos \"río\" y \"banco\", pero la forma de \"banco\" varía. ¡Veamos si las formas de las palabras influyen!" ] }, { @@ -542,7 +538,7 @@ "id": "217561a7-8dfe-4537-839d-0fa6b9063d9e", "metadata": {}, "source": [ - "🔔 **Question**: Why do \"banks\" and \"river\" have a higher similarity score than other pairs?" + "🔔 **Pregunta**: ¿Por qué \"bancos\" y \"río\" tienen un puntaje de similitud más alto que otros pares?" ] }, { @@ -550,11 +546,11 @@ "id": "f0ec2123-05ec-46f8-b042-e761e72f1992", "metadata": {}, "source": [ - "## 🥊 Challenge 1: Dosen't Match\n", + "## 🥊 Desafío 1: No coinciden\n", "\n", - "Now it's your turn! In the following cell, we have prepared a list of coffee-noun pairs, i.e., the word \"coffee\" is paired with the name of a specific coffee drink. Let's find out which coffee drink is considered most similar to \"coffee\" and which one is not. \n", + "¡Ahora te toca! En la siguiente celda, hemos preparado una lista de pares de sustantivos con \"café\". Es decir, la palabra \"café\" está emparejada con el nombre de una bebida de café específica. Averigüemos qué bebida de café se considera más similar a \"café\" y cuál no.\n", "\n", - "Complete the for loop (two cells below) to calculate the cosine similarity between each pair of words by using the `similarity` function. " + "Completa el bucle for (dos celdas a continuación) para calcular la similitud de coseno entre cada par de palabras usando la función \"similitud\"." ] }, { @@ -590,9 +586,9 @@ "id": "f09e021f-b91a-4c41-ba71-97bba798bb4e", "metadata": {}, "source": [ - "Next, let's focus on verbs commonly associated with coffee-making. Take a look at the use case for the [`doesnt_match`](https://radimrehurek.com/gensim/auto_examples/tutorials/run_word2vec.html#word2vec-demo) function and then use it to identify the verb that does not seem to belong.\n", + "A continuación, centrémonos en los verbos comúnmente asociados con la preparación de café. Analicemos el caso de uso de la función [`doesnt_match`](https://radimrehurek.com/gensim/auto_examples/tutorials/run_word2vec.html#word2vec-demo) y luego úsela para identificar el verbo que no parece corresponder.\n", "\n", - "Feel free to add more verbs to the list!" + "¡Agregue más verbos a la lista!" ] }, { @@ -621,7 +617,7 @@ "id": "7ad4e99f-6048-43a8-a698-ed7e5051a4dc", "metadata": {}, "source": [ - "🔔 **Question**: What have you found? Share your answers in the chat! " + "🔔 **Pregunta**: ¿Qué encontraste? ¡Comparte tus respuestas en el chat!" ] }, { @@ -631,35 +627,33 @@ "source": [ "\n", "\n", - "# Word Analogy\n", - "\n", - "In addition to similarities between word pairs, one of the best known ways to use word vectors provided by `word2vec` is to solve word analogies. For example, consider the following analogy: \n", + "# Analogía de Palabras\n", "\n", - "`man : king :: woman : queen`\n", + "Además de las similitudes entre pares de palabras, una de las maneras más conocidas de usar los vectores de palabras proporcionados por `word2vec` es resolver analogías de palabras. Por ejemplo, considere la siguiente analogía:\n", "\n", - "Oftentimes, word analogy like this is visualized with parallelogram, such as shown in the following figure, which is adapted from [Ethayarajh et al. (2019)](https://arxiv.org/abs/1810.04882). \n", + "`hombre: rey :: mujer: reina`\n", "\n", + "A menudo, analogías de palabras como esta se visualizan con un paralelogramo, como se muestra en la siguiente figura, adaptada de [Ethayarajh et al. (2019)](https://arxiv.org/abs/1810.04882).\n", "\"Word\n", "\n", - "The upper side (difference between `man` and `woman`) should approximate the lower side (difference between `king` and `queen`); the vector difference represents the meanig of `female`. \n", + "El lado superior (diferencia entre `hombre` y `mujer`) debe aproximarse al lado inferior (diferencia entre `rey` y `reina`); la diferencia vectorial representa el significado de `mujer`.\n", "\n", - "- $\\mathbf{V}_{\\text{man}} - \\mathbf{V}_{\\text{woman}} \\approx \\mathbf{V}_{\\text{king}} - \\mathbf{V}_{\\text{queen}}$\n", + "- $\\mathbf{V}_{\\text{hombre}} - \\mathbf{V}_{\\text{mujer}} \\approx \\mathbf{V}_{\\text{rey}} - \\mathbf{V}_{\\text{reina}}$\n", "\n", - "Similarly, the left side (difference between `king` and `man`) should approximate the right side (difference between `queen` and `woman`); the vector difference represents the meaning of `royal`.\n", + "De igual manera, el lado izquierdo (diferencia entre `rey` y `hombre`) debe aproximarse al lado derecho (diferencia entre `reina` y `mujer`); la diferencia vectorial representa el significado de `realeza`.\n", "\n", - "- $\\mathbf{V}_{\\text{king}} - \\mathbf{V}_{\\text{man}} \\approx \\mathbf{V}_{\\text{queen}} - \\mathbf{V}_{\\text{woman}}$\n", + "- $\\mathbf{V}_{\\text{rey}} - \\mathbf{V}_{\\text{hombre}} \\approx \\mathbf{V}_{\\text{reina}} - \\mathbf{V}_{\\text{mujer}}$\n", "\n", - "We can take either equation and rearrange it:\n", + "Podemos tomar cualquiera de las ecuaciones y reorganizarlas:\n", "\n", - "- $\\mathbf{V}_{\\text{king}} - \\mathbf{V}_{\\text{man}} + \\mathbf{V}_{\\text{woman}} \\approx \\mathbf{V}_{\\text{Queen}}$\n", + "- $\\mathbf{V}_{\\text{rey}} - \\mathbf{V}_{\\text{hombre}} + \\mathbf{V}_{\\text{mujer}} \\approx \\mathbf{V}_{\\text{Reina}}$\n", "\n", - "If the vectors of `king`, `man`, and `woman` are known, we can use simple vector arithmetic to obtain a vector that approximates the meaning of `queen`. This is the idea behind solving word analogies with word embeddings.\n", + "Si conocemos los vectores de `rey`, `hombre` y `mujer`, podemos usar aritmética vectorial simple para obtener un vector que se aproxime al significado de `reina`. Esta es la idea detrás de resolver analogías de palabras con incrustaciones de palabras.\n", "\n", - "Let's implement it!\n", + "¡Vamos a implementarlo!\n", + "En las siguientes operaciones, usamos la función [`get_vector`](https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.KeyedVectors.get_vector) para obtener el vector de una palabra. Esta función funciona de forma similar a usar una clave para acceder a su valor en el diccionario `word2vec`, pero también nos permite especificar si queremos normalizar el vector.\n", "\n", - "In the following operations, we use the function [`get_vector`](https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.KeyedVectors.get_vector) to obtain a vector for a word. The function works similarly to using a key to access its value in the `word2vec` dictionary, but it also allows us to specify whether we want to normalize the vector. \n", - "\n", - "We want to set `norm` to `True` and renormalize the difference vector later. This is because different vectors have different lengths; normalization puts everything on a common scale." + "Queremos establecer `norm` en `True` y renormalizar el vector de diferencia posteriormente. Esto se debe a que los distintos vectores tienen longitudes diferentes; la normalización establece todo en una escala común." ] }, { @@ -715,11 +709,11 @@ "id": "680c755c-f22c-4e77-b8c2-c65a2f5a95a6", "metadata": {}, "source": [ - "🔔 **Question**: The word \"queen\" is the second most similar one—not bad! Wait, why does \"king\" have the highest similarity score?\n", + "🔔 **Pregunta**: La palabra \"queen\" es la segunda más similar, ¡nada mal! Un momento, ¿por qué \"king\" tiene la mayor similitud?\n", "\n", - "Carrying out these operations can be done in one swoop with the `most_similar` function. \n", + "Estas operaciones se pueden realizar de una sola vez con la función `most_similar`.\n", "\n", - "We need to specify two arguments, `positive` and `negative`. The argument `positive` holds the words that we want the output to be similar to, and `negative` the words we'd like the output to be dissimilar to." + "Necesitamos especificar dos argumentos: `positive` y `negative`. El argumento `positive` contiene las palabras con las que queremos que el resultado sea similar, y `negative`, las palabras con las que queremos que el resultado sea diferente." ] }, { @@ -758,7 +752,7 @@ "id": "421f5786-0b88-41f4-95b3-353311a7c8bf", "metadata": {}, "source": [ - "You may have noticed that the word \"king\" is no longer in the result. That's because the `most_similar` function, by default, skips the input words when returning the result. This makes sense—the word itself would have the highest cosine similarity, but it is not an informative answer to our query. " + "Quizás hayas notado que la palabra \"king\" ya no aparece en el resultado. Esto se debe a que la función `most_similar`, por defecto, omite las palabras de entrada al devolver el resultado. Esto tiene sentido: la palabra en sí tendría la mayor similitud de coseno, pero no es una respuesta informativa a nuestra consulta." ] }, { @@ -766,13 +760,13 @@ "id": "b91687e2-62dc-4c20-adf7-75f2504df0ce", "metadata": {}, "source": [ - "## 🥊 Challenge 2: Woman is to Homemaker?\n", + "## 🥊 Desafío 2: ¿Mujer es amas de casa?\n", "\n", - "[Bolukbasi et al. (2016)](https://arxiv.org/abs/1607.06520) is a thought-provoking investigation of gender bias in word embeddings, and they primarily focus on word analogies, especially those that reveal gender stereotyping. Let run a couple examples discussed in the paper, using the `most_similiar` function we've just learned. \n", + "[Bolukbasi et al. (2016)](https://arxiv.org/abs/1607.06520) es una investigación que invita a la reflexión sobre el sesgo de género en las incrustaciones de palabras, y se centra principalmente en las analogías de palabras, especialmente aquellas que revelan estereotipos de género. Ejecutemos un par de ejemplos analizados en el artículo, utilizando la función `most_similiar` que acabamos de aprender.\n", "\n", - "The following cell contains a few examples we can pass to the `positive` and `negative` arguments. For example, we want the output to be similar to \"woman\" and \"chairman\" but dissimilar to \"man.\" We'll print the top result by indexing the 0th item. \n", + "La siguiente celda contiene algunos ejemplos que podemos pasar a los argumentos `positive` y `negative`. Por ejemplo, queremos que la salida sea similar a \"woman\" y \"chairman\", pero diferente a \"man\". Imprimiremos el resultado superior indexando el elemento 0.\n", "\n", - "Let's complete the following for loop." + "Completemos el siguiente bucle `for`." ] }, { @@ -805,7 +799,7 @@ "id": "eeb6a4d3-ca70-4820-a570-198816a13f7f", "metadata": {}, "source": [ - "🔔 **Question**: What do you find most surprising or unsurprising about these results?" + "🔔 **Pregunta**: ¿Qué es lo que te sorprende más o lo que no te sorprende más de estos resultados?" ] }, { @@ -815,15 +809,15 @@ "source": [ "\n", "\n", - "# Bias in Word Embeddings\n", + "# Sesgo en las incrustaciones de palabras\n", "\n", - "### `GloVe` \n", + "### `GloVe`\n", "\n", - "Any forms of stereotyping is disturbing. Now that we've known gender bias is indeed present in the pretrained embeddings, let's take a more in-depth look at it.\n", + "Cualquier tipo de estereotipo es preocupante. Ahora que sabemos que el sesgo de género está presente en las incrustaciones preentrenadas, analicémoslo con más detalle.\n", "\n", - "We will switch gears to a smaller word embedding model—pretrained `GloVe`. Let's load it with the `api.load()` function. \n", + "Pasaremos a un modelo de incrustación de palabras más pequeño: `GloVe` preentrenado. Lo cargaremos con la función `api.load()`.\n", "\n", - "The `GloVe` mode is trained from Wikipedia and Gigaword (news data). Check out the [documentation](https://nlp.stanford.edu/projects/glove/) for more detailed model descriptions." + "El modo `GloVe` se entrena a partir de Wikipedia y Gigaword (datos de noticias). Consulta la [documentación](https://nlp.stanford.edu/projects/glove/) para obtener descripciones más detalladas del modelo." ] }, { @@ -841,7 +835,7 @@ "id": "0e298be4-6521-4af7-82eb-e3a607ea5938", "metadata": {}, "source": [ - "Let's double check the dimension of the vector, using the \"banana\" example again. " + "Verifiquemos nuevamente la dimensión del vector, usando nuevamente el ejemplo del \"banana\"." ] }, { @@ -870,45 +864,41 @@ "id": "56330365-6bcd-4fd5-b28a-0eb34ee66634", "metadata": {}, "source": [ - "### Semantic Axis\n", + "### Eje Semántico\n", "\n", - "To investigate gender bias in word embeddings, we first need a vector that captures the concept of gender. The idea is to construct **a semantic axis** for this concept. \n", + "Para investigar el sesgo de género en las incrustaciones de palabras, primero necesitamos un vector que capture el concepto de género. La idea es construir **un eje semántico** para este concepto.\n", "\n", - "The rationale for using a semantic axis is that a concept is often complex and cannot be sufficiently denoted by a single word. It is also fluid, meaning that its meaning is not definite but can span form one end of an axis to the other. Once we have the vector representation of a concept, we can project a list of terms onto that axis to see if a term is more aligned towards one end or the other. \n", + "La razón para usar un eje semántico es que un concepto suele ser complejo y no puede denotarse adecuadamente con una sola palabra. Además, es fluido, lo que significa que su significado no es definitivo, sino que puede extenderse de un extremo a otro de un eje. Una vez que tenemos la representación vectorial de un concepto, podemos proyectar una lista de términos sobre ese eje para ver si un término está más alineado hacia un extremo u otro.\n", "\n", - "We follow [An et al. 2018](https://aclanthology.org/P18-1228/) to construct a semantic axis. In preparation, we first need to come up with two sets of pole words that have opposite meanings.\n", + "Seguimos a [An et al. 2018](https://aclanthology.org/P18-1228/) para construir un eje semántico. Como preparación, primero necesitamos crear dos conjuntos de palabras polares con significados opuestos.\n", "\n", "- $\\mathbf{W}_{\\text{plus}} = \\{w_{1}^{+}, w_{2}^{+}, w_{3}^{+}, ..., w_{i}^{+}\\}$\n", "\n", "- $\\mathbf{W}_{\\text{minus}} = \\{w_{1}^{-}, w_{2}^{-}, w_{3}^{-}, ..., w_{j}^{-}\\}$\n", "\n", - "We then take the mean of each vector set to represent the core meaning of that set. \n", - "\n", + "Luego tomamos la media de cada conjunto de vectores para representar el significado central de ese conjunto.\n", "- $\\mathbf{V}_{\\text{plus}} = \\frac{1}{i}\\sum_{1}^{i}w_{i}^{+}$\n", "\n", "- $\\mathbf{V}_{\\text{minus}} = \\frac{1}{j}\\sum_{1}^{j}w_{j}^{-}$\n", "\n", - "Next, we take the difference between the two means to represent the semantic axis of the intended concept. \n", - "\n", + "A continuación, tomamos la diferencia entre ambos medios para representar el eje semántico del concepto pretendido.\n", "- $\\mathbf{V}_{\\text{axis}} = \\mathbf{V}_{\\text{plus}} - \\mathbf{V}_{\\text{minus}}$\n", "\n", - "Projecting a specific term to the semantic axis is, as we've learned above, operationalized as taking the cosine similarity between the word's vector and the semantic axis vector. A positive value would indicate that the term is closer to the $\\mathbf{V}_{\\text{plus}}$ end. A negative value means proximity to the $\\mathbf{V}_{\\text{minus}}$ end. \n", - "\n", + "Como vimos anteriormente, proyectar un término específico al eje semántico se operacionaliza tomando la similitud del coseno entre el vector de la palabra y el vector del eje semántico. Un valor positivo indicaría que el término está más cerca del extremo $\\mathbf{V}_{\\text{plus}}$. Un valor negativo significa proximidad al extremo $\\mathbf{V}_{\\text{minus}}$.\n", "- $score(w) = cos(v_{w}, \\mathbf{V}_{\\text{axis}})$\n", "\n", - "With this tool, we can go ahead and construct a vector for the concept \"gender\"; however, this method is still limited, as gender identity in the real world cannot just be reduced to two polarities. As we proceed, we will discover how much stereotypying is encoded in gender terms.\n", + "Con esta herramienta, podemos construir un vector para el concepto \"género\"; sin embargo, este método aún presenta limitaciones, ya que la identidad de género en el mundo real no puede reducirse simplemente a dos polaridades. A medida que avancemos, descubriremos cuántos estereotipos se codifican en términos de género.\n", "\n", - "## 🥊 Challenge 3: Construct a Semantic Axis\n", + "## 🥊 Desafío 3: Construir un Eje Semántico\n", "\n", - "The following cell defines a set of \"female\" terms and a set of \"male\" terms; these example words are from [Bolukbasi et al., 2016](https://arxiv.org/abs/1607.06520). \n", + "La siguiente celda define un conjunto de términos \"femeninos\" y un conjunto de términos \"masculinos\"; estos ejemplos provienen de [Bolukbasi et al., 2016](https://arxiv.org/abs/1607.06520).\n", "\n", - "To complete the function `get_semaxis`, you will need to:\n", + "Para completar la función `get_semaxis`, necesitará:\n", "\n", - "- Get the word embeddings for terms in each list and save the embeddings to the corresponding lists `v_plus` and `v_minus`. You can use the `model` argument as a dictionary to retrieve word embeddings. \n", - "- Calculate the mean embedding for each list and save the means to the corresponding variables `v_plus_mean` and `v_minus _mean`.\n", - "- Get the difference between the two means and return the difference vector (i.e., the vector for the semantic axis) \n", + "- Obtener las incrustaciones de palabras de los términos de cada lista y guardarlas en las listas correspondientes `v_plus` y `v_minus`. Puede usar el argumento `model` como diccionario para recuperar las incrustaciones de palabras.\n", + "- Calcular la incrustación media de cada lista y guardar las medias en las variables correspondientes `v_plus_mean` y `v_minus_mean`. - Obtener la diferencia entre las dos medias y devolver el vector de diferencia (es decir, el vector del eje semántico).\n", "\n", - "We have provided some starter code for you (two cells below). If everything runs correctly, the embedding size of the semantic axis should be the same as the size of the input vector. " + "Le proporcionamos un código de inicio (dos celdas a continuación). Si todo funciona correctamente, el tamaño de incrustación del eje semántico debería ser igual al tamaño del vector de entrada. " ] }, { @@ -991,7 +981,7 @@ "id": "748fa605-d07f-45ca-b786-795d034c6a61", "metadata": {}, "source": [ - "The vector for \"gender\" has now been created. The next step is to project a list of terms onto the gender axis. We can continue with the occupation terms we've tested previously in Challenge 2. " + "Ya se ha creado el vector de \"género\". El siguiente paso es proyectar una lista de términos sobre el eje de género. Podemos continuar con los términos de ocupación que probamos previamente en el Desafío 2." ] }, { @@ -1018,7 +1008,7 @@ "id": "1f91f7a7-3f21-47f2-a8e1-233603704b0c", "metadata": {}, "source": [ - "Before calculating the cosine similarity, let's first rate the following occupation terms using your intuition. Ratings should be between $[-1, 1]$. A negative value means the term is closer to the male end; a positive value means it is closer to the female end." + "Antes de calcular la similitud del coseno, evalúemos intuitivamente los siguientes términos ocupacionales. Las calificaciones deben estar entre [-1, 1]. Un valor negativo significa que el término está más cerca del extremo masculino; un valor positivo, del extremo femenino." ] }, { @@ -1094,11 +1084,11 @@ "id": "4c967ce2-1eac-483b-b46e-056bb0b8a8a9", "metadata": {}, "source": [ - "## Visualize the Projection\n", + "## Visualizar la proyección\n", "\n", - "Now that we have calculated the projection of each occupation term onto the gender axis, let's plot these values to gain a more straightforward understanding of how much gender stereotyping is hidden in these terms.\n", + "Ahora que hemos calculado la proyección de cada término de ocupación sobre el eje de género, graficaremos estos valores para comprender mejor cuántos estereotipos de género se esconden en estos términos.\n", "\n", - "We will use a bar plot to visualize the results, using a gradient color palette. The bar's color approximates the proximity of a term to an end." + "Usaremos un gráfico de barras para visualizar los resultados, usando una paleta de colores con degradado. El color de la barra indica la proximidad de un término a su final." ] }, { @@ -1142,9 +1132,9 @@ "id": "56fd4b50-e565-4e50-b063-7b88fba858e0", "metadata": {}, "source": [ - "We will visualize the projections first, but feel free to use the above function to visualize your own ratings. \n", + "Primero visualizaremos las proyecciones, pero pueden usar la función anterior para visualizar sus propias valoraciones.\n", "\n", - "🔔 **Question**: Do you find the results surprising or expected? Let's pause for a minute to discuss why steorotyping exists in word embeddings." + "🔔 **Pregunta**: ¿Les sorprenden o les parecen esperados los resultados? Detengámonos un momento para analizar por qué existe la estereotipación en las incrustaciones de palabras." ] }, { @@ -1190,17 +1180,17 @@ "id": "1490b4ca-41a9-4a0e-99d1-fb247f3927ff", "metadata": {}, "source": [ - "## 🎬 **Demo**: Projections onto Two Axes\n", + "## 🎬 **Demostración**: Proyecciones sobre dos ejes\n", "\n", - "We can also project terms onto **two axes** and plot the results on **a scatter plot**, where the coordinates correspond to projections onto the two axes.\n", + "También podemos proyectar términos sobre **dos ejes** y representar los resultados en **un diagrama de dispersión**, donde las coordenadas corresponden a las proyecciones sobre ambos ejes.\n", "\n", - "Social class is another dimension commonly investigated in the literature. In this demo, we'll create a semantic axis for affluence, one dimension of social class, using two sets of pole words representing two ends of the concept, as described in [Kozlowski et al. 2019](https://journals.sagepub.com/doi/full/10.1177/0003122419877135).\n", + "La clase social es otra dimensión que se investiga con frecuencia en la literatura. En esta demostración, crearemos un eje semántico para la riqueza, una dimensión de la clase social, utilizando dos conjuntos de palabras clave que representan los dos extremos del concepto, como se describe en [Kozlowski et al. 2019](https://journals.sagepub.com/doi/full/10.1177/0003122419877135).\n", "\n", - "In the first example, we'll project a list of **sports terms** onto both the gender and affluence axes. We'll visualize the results on a scatter plot, with the x-axis representing gender and the y-axis representing affluence. The coordinates of each term on this plot correspond to its projections onto these axes.\n", + "En el primer ejemplo, proyectaremos una lista de **términos deportivos** sobre los ejes de género y riqueza. Visualizaremos los resultados en un diagrama de dispersión, donde el eje x representa el género y el eje y la riqueza. Las coordenadas de cada término en este gráfico corresponden a sus proyecciones sobre estos ejes.\n", "\n", - "Next, we'll repeat the process to visualize occupation terms to obtain a concrete idea of how much each term is biased towards either end of these two dimensions.\n", + "A continuación, repetiremos el proceso para visualizar los términos de ocupación y obtener una idea concreta de cuánto se inclina cada término hacia cualquiera de los extremos de estas dos dimensiones.\n", "\n", - "Let's dive in!" + "¡Comencemos!" ] }, { @@ -1225,7 +1215,7 @@ "id": "e2a1ad74-c6a4-46ac-a7ce-78090d283f76", "metadata": {}, "source": [ - "We will project sports terms onto the social class axis to see if some sports are more associated with the \"high\" society and others \"low\" soceity. " + "Proyectaremos términos deportivos sobre el eje de clase social para ver si algunos deportes están más asociados con la sociedad “alta” y otros con la sociedad “baja”." ] }, { @@ -1254,7 +1244,7 @@ "id": "c56c3592-9760-4eb6-acda-bdc931c6284f", "metadata": {}, "source": [ - "Next, let's use the `get_projection` function to calculate the cosine similarity between each sport term and each semantic axis. " + "A continuación, utilicemos la función `get_projection` para calcular la similitud del coseno entre cada término deportivo y cada eje semántico." ] }, { @@ -1273,7 +1263,7 @@ "id": "7a1ec3d1-609a-4d2f-b9b3-25131a536e89", "metadata": {}, "source": [ - "Finally, let's visualize the results using a scatter plot." + "Por último, visualicemos los resultados utilizando un diagrama de dispersión." ] }, { @@ -1332,13 +1322,13 @@ "id": "99b30b78-dd17-4bd5-9028-29e3f37cb963", "metadata": {}, "source": [ - "🔔 **Question**: Let's take a minute to unpack the plot and discuss the following questions:\n", - "- Which sport term appears most biased towards the male end, and which towards the female end?\n", - "- Which sport appears to be gender-neutral?\n", - "- Which sport term appears most biased towards the affluent end, and which one towards the other end?\n", - "- Which sport seems neutral with respect to affluence?\n", + "🔔**Pregunta**: Dediquemos un minuto a analizar la trama y a debatir las siguientes preguntas:\n", + "- ¿Qué término deportivo parece más sesgado hacia el público masculino y cuál hacia el femenino?\n", + "- ¿Qué deporte parece ser neutral en cuanto al género?\n", + "- ¿Qué término deportivo parece más sesgado hacia el público adinerado y cuál hacia el otro?\n", + "- ¿Qué deporte parece neutral en cuanto a la riqueza?\n", "\n", - "We have analyzed the gender bias in the occupation terms. To probe them further, let's take their projections onto the affluence axis into account." + "Hemos analizado el sesgo de género en los términos de ocupación. Para profundizar en ellos, consideremos sus proyecciones sobre el eje de la riqueza." ] }, { @@ -1410,11 +1400,11 @@ "id": "9f93b7bf-f88e-460d-bcf7-f760597da95c", "metadata": {}, "source": [ - "🔔 **Question**: The affluence axis provides a new perspective. Again, let's pause and discuss the following questions.\n", + "🔔 **Pregunta**: El eje de la afluencia ofrece una nueva perspectiva. De nuevo, detengámonos y analicemos las siguientes preguntas.\n", "\n", - "- Which occupation term immediately caught your eye, and why? \n", - "- Which occuptation appears most biased towards the affluent end , and which one towards the other end?\n", - "- Which occputation seems neutral with respect to affluence?" + "- ¿Qué término ocupacional le llamó la atención de inmediato y por qué?\n", + "- ¿Qué ocupación parece más sesgada hacia el extremo afluente y cuál hacia el otro extremo?\n", + "- ¿Qué ocupación parece neutral con respecto a la afluencia?" ] }, { @@ -1422,9 +1412,9 @@ "id": "40ec74c2-44d0-4061-888c-bb1d7e9e436a", "metadata": {}, "source": [ - "We will wrap up this workshop with these two plots, and hopefully, they will leave you with some food for thought to further explore word embeddings. Constructing a semantic axis for a cultural dimension, such as gender or affluence, is widely researched. With this tool in hand, we can investigate concepts beyond culture. It could be a useful method for capturing the abstract meanings of various notions, such as an axis of coldness, an axis of kindness, and so on. \n", + "Concluiremos este taller con estos dos diagramas, que esperamos les inspiren a seguir explorando las incrustaciones de palabras. La construcción de un eje semántico para una dimensión cultural, como el género o la riqueza, es un tema ampliamente investigado. Con esta herramienta, podemos investigar conceptos más allá de la cultura. Podría ser un método útil para captar los significados abstractos de diversas nociones, como el eje de la frialdad, el eje de la amabilidad, etc.\n", "\n", - "Topics introduced in this workshop benefit greatly from research advances in the field of NLP. Check out the reference section if you would like to take a look at the papers that inspired the materials covered in this notebook!" + "Los temas presentados en este taller se benefician enormemente de los avances de la investigación en el campo de la PNL. ¡Consulten la sección de referencias si desean consultar los artículos que inspiraron los materiales de este cuaderno!" ] }, { @@ -1432,14 +1422,14 @@ "id": "65af9f01-45e0-4aba-b443-dedb233a1ee6", "metadata": {}, "source": [ - "# References\n", + "Referencias\n", + "\n", + "1. [word2vec](https://arxiv.org/abs/1301.3781): Mikolov, T., Chen, K., Corrado, G. y Dean, J. (2013). Estimación eficiente de representaciones de palabras en el espacio vectorial. arXiv:1301.3781.\n", + "\n", + "2. [GloVe](https://aclanthology.org/D14-1162/): Pennington, J., Socher, R. y Manning, C. D. (2014). GloVe: Vectores globales para la representación de palabras. En *Actas de la Conferencia de 2014 sobre Métodos Empíricos en el Procesamiento del Lenguaje Natural*, 1532–1543. 5. [Analogías de palabras](https://arxiv.org/abs/1810.04882): Ethayarajh, K., Duvenaud, D. y Hirst, G. (2018). Hacia la comprensión de las analogías lineales de palabras. En *Actas de la 57.ª Reunión Anual de la Asociación de Lingüística Computacional*, 3253–3262.\n", "\n", - "1. [word2vec](https://arxiv.org/abs/1301.3781): Mikolov, T., Chen, K., Corrado, G., & Dean, J. (2013). Efficient estimation of word representations in vector space. arXiv:1301.3781.\n", - "2. [GloVe](https://aclanthology.org/D14-1162/): Pennington, J., Socher, R., & Manning, C. D. (2014). GloVe: Global vectors for word representation. In *Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing*, 1532–1543.\n", - "5. [Word analogies](https://arxiv.org/abs/1810.04882): Ethayarajh, K., Duvenaud, D., & Hirst, G. (2018). Towards understanding linear word analogies. In *Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics*, 3253–3262.\n", - "8. [Semantic axis](https://aclanthology.org/P18-1228/): An, J., Kwak, H. & Ahn, Y.-Y. (2018). Semaxis: A lightweight framework to characterize domain-specific word semantics beyond sentiment. In *Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics 1*, 2450–2461.\n", - "9. [Bias in word embeddings](https://arxiv.org/abs/1607.06520): Bolukbasi, T., Chang, K. W., Zou, J. Y., Saligrama, V., & Kalai, A. T. (2016). Man is to computer programmer as woman is to homemaker? Debiasing word embeddings. *Advances in Neural Information Processing Systems, 29,* 4349–4357.\n", - "10. [Cultural dimensions and word embeddings](https://journals.sagepub.com/doi/10.1177/0003122419877135): Kozlowski, A. C., Taddy, M., & Evans, J. A. (2019). The geometry of culture: Analyzing the meanings of class through word embeddings. *American Sociological Review, 84*(5), 905-949." + "8. [Eje semántico](https://aclanthology.org/P18-1228/): An, J., Kwak, H. y Ahn, Y.-Y. (2018). Semaxis: Un marco ligero para caracterizar la semántica de palabras de dominio específico más allá del sentimiento. En *Actas de la 56.ª Reunión Anual de la Asociación de Lingüística Computacional 1*, 2450–2461. 9. [Sesgo en las incrustaciones de palabras](https://arxiv.org/abs/1607.06520): Bolukbasi, T., Chang, K. W., Zou, J. Y., Saligrama, V. y Kalai, A. T. (2016). ¿El hombre es al programador informático lo que la mujer es al ama de casa? Eliminando el sesgo de las incrustaciones de palabras. *Advances in Neural Information Processing Systems, 29,* 4349–4357.\n", + "10. [Dimensiones culturales e incrustaciones de palabras](https://journals.sagepub.com/doi/10.1177/0003122419877135): Kozlowski, A. C., Taddy, M. y Evans, J. A. (2019). La geometría de la cultura: Análisis de los significados de clase a través de las incrustaciones de palabras. *Revista Sociológica Americana, 84*(5), 905-949." ] }, { @@ -1449,11 +1439,11 @@ "source": [ "
\n", "\n", - "## ❗ Key Points\n", + "## ❗ Puntos clave\n", "\n", - "* Pre-trained word embeddings like `word2vec` and `GloVe` take contextual information into representations of words' meanings. \n", - "* Similarities between words is conveniently reflected in cosine similarity. \n", - "* We can explore biases in word embeddings with the methods of semantic axis.\n", + "* Las incrustaciones de palabras preentrenadas, como `word2vec` y `GloVe`, incorporan la información contextual a las representaciones del significado de las palabras.\n", + "* Las similitudes entre palabras se reflejan convenientemente en la similitud de cosenos.\n", + "* Podemos explorar sesgos en las incrustaciones de palabras con los métodos de ejes semánticos.\n", "\n", "
" ] From fe15426a2a16c77e8ad190134ea02ad16cdcb8d9 Mon Sep 17 00:00:00 2001 From: rebe1603 Date: Tue, 26 Aug 2025 10:31:44 -0500 Subject: [PATCH 3/4] =?UTF-8?q?Traduccion=20al=20espa=C3=B1ol=20de=20word?= =?UTF-8?q?=20embeddings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lessons/03_word_embeddings.ipynb | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lessons/03_word_embeddings.ipynb b/lessons/03_word_embeddings.ipynb index b8930bd..c04ef46 100644 --- a/lessons/03_word_embeddings.ipynb +++ b/lessons/03_word_embeddings.ipynb @@ -577,7 +577,8 @@ "outputs": [], "source": [ "for w1, w2 in coffee_nouns:\n", - " similarity = # YOUR CODE HERE\n", + " # YOUR CODE HERE\n", + " similarity = None\n", " print(f\"{w1}, {w2}, {similarity}\")" ] }, @@ -608,7 +609,8 @@ "metadata": {}, "outputs": [], "source": [ - "verb_dosent_match = # YOUR CODE HERE\n", + "verb_dosent_match = None\n", + "# YOUR CODE HERE\n", "verb_dosent_match" ] }, @@ -790,7 +792,8 @@ "outputs": [], "source": [ "for example in positive_pair:\n", - " result = # YOUR CODE HERE\n", + " result = None\n", + " # YOUR CODE HERE\n", " print(f\"man is to {example[1]} as woman to {result[0][0]}\")" ] }, From c501230fbf41febae429b8396a3a1844b0cd462c Mon Sep 17 00:00:00 2001 From: ANGEL MERINO Date: Tue, 26 Aug 2025 10:45:37 -0500 Subject: [PATCH 4/4] Upgrade --- solutions/03_word_embeddings_solutions.ipynb | 64 ++++++++++++++++++++ solutions/get_semaxis.py | 0 2 files changed, 64 insertions(+) create mode 100644 solutions/get_semaxis.py diff --git a/solutions/03_word_embeddings_solutions.ipynb b/solutions/03_word_embeddings_solutions.ipynb index aa9814a..ea91e81 100644 --- a/solutions/03_word_embeddings_solutions.ipynb +++ b/solutions/03_word_embeddings_solutions.ipynb @@ -459,6 +459,70 @@ " embedding_size=50)\n", "gender_axis" ] + }, + { + "cell_type": "markdown", + "id": "f4ed6323", + "metadata": {}, + "source": [ + "\n", + "¡Listo! Aquí tienes la función get_semaxis completa y un poco más robusta (filtra OOV y opcionalmente normaliza el eje). Con GloVe-50, el vector resultante queda de tamaño 50." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "28cdd8d1", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import gensim.downloader as api\n", + "\n", + "# Cargar GloVe 50D\n", + "glove = api.load('glove-wiki-gigaword-50')\n", + "\n", + "# Polos (Bolukbasi et al., 2016)\n", + "female = ['she', 'woman', 'female', 'daughter', 'mother', 'girl']\n", + "male = ['he', 'man', 'male', 'son', 'father', 'boy']\n", + "\n", + "def get_semaxis(list1, list2, model, embedding_size, normalize=True):\n", + " \"\"\"Calcula el embedding de un eje semántico dadas dos listas de palabras polo.\"\"\"\n", + " # 1) Filtrar palabras fuera de vocabulario (OOV)\n", + " in_vocab1 = [w for w in list1 if w in model.key_to_index]\n", + " in_vocab2 = [w for w in list2 if w in model.key_to_index]\n", + " if not in_vocab1 or not in_vocab2:\n", + " raise ValueError(\"Alguna de las listas quedó vacía tras filtrar palabras OOV.\")\n", + "\n", + " # 2) Obtener embeddings y promediar cada polo\n", + " v_plus = np.vstack([model[w] for w in in_vocab1]) # polo positivo\n", + " v_minus = np.vstack([model[w] for w in in_vocab2]) # polo negativo\n", + " v_plus_mean = v_plus.mean(axis=0)\n", + " v_minus_mean = v_minus.mean(axis=0)\n", + "\n", + " # 3) Diferencia de medios = eje semántico\n", + " sem_axis = v_plus_mean - v_minus_mean\n", + "\n", + " # (Opcional) normalizar a unidad, útil para proyecciones consistentes\n", + " if normalize:\n", + " norm = np.linalg.norm(sem_axis)\n", + " if norm > 0:\n", + " sem_axis = sem_axis / norm\n", + "\n", + " # Sanity check\n", + " assert sem_axis.size == embedding_size\n", + " return sem_axis\n", + "\n", + "# Calcular el eje de género\n", + "gender_axis = get_semaxis(\n", + " list1=female,\n", + " list2=male,\n", + " model=glove,\n", + " embedding_size=50\n", + ")\n", + "\n", + "gender_axis, gender_axis.shape # -> (array([...]), (50,))\n" + ] } ], "metadata": { diff --git a/solutions/get_semaxis.py b/solutions/get_semaxis.py new file mode 100644 index 0000000..e69de29