knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%" ) set.seed(46709394) devtools::load_all()
The goal of sweater (Speedy Word Embedding Association Test & Extras using R) is to test for associations among words in word embedding spaces. The methods provided by this package can also be used to test for unwanted associations, or biases.
The package provides functions that are speedy. They are either implemented in C++, or are speedy but accurate approximation of the original implementation proposed by Caliskan et al (2017). See the benchmark here.
This package provides extra methods such as Relative Norm Distance, Embedding Coherence Test, SemAxis and Relative Negative Sentiment Bias.
If your goal is to reproduce the analysis in Caliskan et al (2017), please consider using the original Java program or the R package cbn by Lowe. To reproduce the analysis in Garg et al (2018), please consider using the original Python program. To reproduce the analysis in Mazini et al (2019), please consider using the original Python program.
Please cite this software as:
Chan, C., (2022). sweater: Speedy Word Embedding Association Test and Extras Using R. Journal of Open Source Software, 7(72), 4036, https://doi.org/10.21105/joss.04036
For a BibTeX entry, use the output from citation(package = "sweater")
.
Recommended: install the latest development version
remotes::install_github("gesistsa/sweater")
or the "stable" release
install.packages("sweater")
All tests in this package use the concept of queries (see Badilla et al., 2020) to study associations in the input word embeddings w
. This package uses the "STAB" notation from Brunet et al (2019). [^1]
[^1]: In the pre 0.1.0 version of this package, the package used S
, T
, A
, and B
as the main parameters. It was later rejected because the symbol T
is hardlinked to the logical value TRUE
as a global variable; and it is considered to be a bad style to use the symbol T
. Accordingly, they were renamed to S_words
, T_words
, A_words
, and B_words
respectively. But in general, please stop using the symbol T
to represent TRUE
!
All tests depend on two types of words. The first type, namely, S_words
and T_words
, is target words (or neutral words in Garg et al). In the case of studying biases, these are words that should have no bias. For instance, the words such as "nurse" and "professor" can be used as target words to study the gender bias in word embeddings. One can also separate these words into two sets, S_words
and T_words
, to group words by their perceived bias. For example, Caliskan et al. (2017) grouped target words into two groups: mathematics ("math", "algebra", "geometry", "calculus", "equations", "computation", "numbers", "addition") and arts ("poetry", "art", "dance", "literature", "novel", "symphony", "drama", "sculpture"). Please note that also T_words
is not always required.
The second type, namely A_words
and B_words
, is attribute words (or group words in Garg et al). These are words with known properties in relation to the bias that one is studying. For example, Caliskan et al. (2017) used gender-related words such as "male", "man", "boy", "brother", "he", "him", "his", "son" to study gender bias. These words qualify as attribute words because we know they are related to a certain gender.
It is recommended using the function query()
to make a query and calculate_es()
to calculate the effect size.
| Target words | Attribute words | Method | method
argument | Suggested by query
? | legacy functions [^legacy] |
|------------------|------------------|-------------------------------------------------------------|-------------------|-----------------------|----------------------------------------------------|
| S_words | A_words | Mean Average Cosine Similarity (Mazini et al. 2019) | "mac" | yes | mac(), mac_es() |
| S_words | A_words, B_words | Relative Norm Distance (Garg et al. 2018) | "rnd" | yes | rnd(), rnd_es() |
| S_words | A_words, B_words | Relative Negative Sentiment Bias (Sweeney & Najafian. 2019) | "rnsb" | no | rnsb(), rnsb_es() |
| S_words | A_words, B_words | Embedding Coherence Test (Dev & Phillips. 2019) | "ect" | no | ect(), ect_es(), plot_ect() |
| S_words | A_words, B_words | SemAxis (An et al. 2018) | "semaxis" | no | semaxis() |
| S_words | A_words, B_words | Normalized Association Score (Caliskan et al. 2017) | "nas" | no | nas() |
| S_words, T_words | A_words, B_words | Word Embedding Association Test (Caliskan et al. 2017) | "weat" | yes | weat(), weat_es(), weat_resampling(), weat_exact() |
| S_words, T_words | A_words, B_words | Word Embeddings Fairness Evaluation (Badilla et al. 2020) | To be implemented | | |
The simplest form of bias detection is Mean Average Cosine Similarity (Mazini et al. 2019). The same method was used in Kroon et al. (2020). googlenews
is a subset of the pretrained word2vec word embeddings provided by Google.
By default, the query()
function guesses the method you want to use based on the combination of target words and attribute words provided (see the "Suggested?" column in the above table). You can also make this explicit by specifying the method
argument. Printing the returned object shows the effect size (if available) as well as the functions that can further process the object: calculate_es
and plot
. Please read the help file of calculate_es
(?calculate_es
) on what is the meaning of the effect size for a specific test.
require(sweater)
S1 <- c("janitor", "statistician", "midwife", "bailiff", "auctioneer", "photographer", "geologist", "shoemaker", "athlete", "cashier", "dancer", "housekeeper", "accountant", "physicist", "gardener", "dentist", "weaver", "blacksmith", "psychologist", "supervisor", "mathematician", "surveyor", "tailor", "designer", "economist", "mechanic", "laborer", "postmaster", "broker", "chemist", "librarian", "attendant", "clerical", "musician", "porter", "scientist", "carpenter", "sailor", "instructor", "sheriff", "pilot", "inspector", "mason", "baker", "administrator", "architect", "collector", "operator", "surgeon", "driver", "painter", "conductor", "nurse", "cook", "engineer", "retired", "sales", "lawyer", "clergy", "physician", "farmer", "clerk", "manager", "guard", "artist", "smith", "official", "police", "doctor", "professor", "student", "judge", "teacher", "author", "secretary", "soldier") A1 <- c("he", "son", "his", "him", "father", "man", "boy", "himself", "male", "brother", "sons", "fathers", "men", "boys", "males", "brothers", "uncle", "uncles", "nephew", "nephews") ## The same as: ## mac_neg <- query(googlenews, S_words = S1, A_words = A1, method = "mac") mac_neg <- query(googlenews, S_words = S1, A_words = A1) mac_neg
The returned object is an S3 object. Please refer to the help file of the method for the definition of all slots (in this case: ?mac
). For example, the magnitude of bias for each word in S1
is available in the P
slot.
sort(mac_neg$P)
This analysis reproduces the analysis in Garg et al (2018), namely Figure 1.
B1 <- c("she", "daughter", "hers", "her", "mother", "woman", "girl", "herself", "female", "sister", "daughters", "mothers", "women", "girls", "females", "sisters", "aunt", "aunts", "niece", "nieces" ) garg_f1 <- query(googlenews, S_words = S1, A_words = A1, B_words = B1) garg_f1
The object can be plotted by the function plot
to show the bias of each word in S. Words such as "nurse", "midwife" and "librarian" are more associated with female, as indicated by the positive relative norm distance.
plot(garg_f1)
The effect size is simply the sum of all relative norm distance values (Equation 3 in Garg et al. 2018). It is displayed simply by printing the object. You can also use the function calculate_es
to obtain the numeric result.
The more positive effect size indicates that words in S_words
are more associated with B_words
. As the effect size is negative, it indicates that the concept of occupation is more associated with A_words
, i.e. male.
calculate_es(garg_f1)
This analysis attempts to reproduce the analysis in An et al. (2018).
You may obtain the word2vec word vectors trained with Trump supporters Reddit from here. This package provides a tiny version of the data small_reddit
for reproducing the analysis.
S2 <- c("mexicans", "asians", "whites", "blacks", "latinos") A2 <- c("respect") B2 <- c("disrespect") res <- query(small_reddit, S_words = S2, A_words = A2, B_words = B2, method = "semaxis", l = 1) plot(res)
Embedding Coherence Test (Dev & Phillips, 2019) is similar to SemAxis. The only significant difference is that no "SemAxis" is calculated (the difference between the average word vectors of A_words
and B_words
). Instead, it calculates two separate axes for A_words
and B_words
. Then it calculates the proximity of each word in S_words
with the two axes. It is like doing two separate mac
, but ect
averages the word vectors of A_words
/ B_words
first.
It is important to note that P
is a 2-D matrix. Hence, the plot is 2-dimensional. Words above the equality line are more associated with B_words
and vice versa.
res <- query(googlenews, S_words = S1, A_words = A1, B_words = B1, method = "ect") res$P plot(res)
Effect size can also be calculated. It is the Spearman Correlation Coefficient of the two rows in P
. Higher value indicates more "coherent", i.e. less bias.
res
This analysis attempts to reproduce the analysis in Sweeney & Najafian (2019).
Please note that the datasets glove_sweeney
, bing_pos
and bing_neg
are not included in the package. If you are interested in reproducing the analysis, the 3 datasets are available from here.
load("tests/testdata/bing_neg.rda") load("tests/testdata/bing_pos.rda") load("tests/testdata/glove_sweeney.rda") S3 <- c("swedish", "irish", "mexican", "chinese", "filipino", "german", "english", "french", "norwegian", "american", "indian", "dutch", "russian", "scottish", "italian") sn <- query(glove_sweeney, S_words = S3, A_words = bing_pos, B_words = bing_neg, method = "rnsb")
The analysis shows that indian
, mexican
, and russian
are more likely to be associated with negative sentiment.
plot(sn)
The effect size from the analysis is the Kullback–Leibler divergence of P from the uniform distribution. It is extremely close to the value reported in the original paper (0.6225).
sn
rnsb
supports quanteda dictionaries as S_words
. This support will be expanded to other methods later.
This analysis uses the data from here.
For example, newsmap_europe
is an abridged dictionary from the package newsmap (Watanabe, 2018). The dictionary contains keywords of European countries and has two levels: regional level (e.g. Eastern Europe) and country level (e.g. Germany).
load("tests/testdata/newsmap_europe.rda") load("tests/testdata/dictionary_demo.rda") require(quanteda) newsmap_europe
Country-level analysis
country_level <- rnsb(w = dictionary_demo, S_words = newsmap_europe, A_words = bing_pos, B_words = bing_neg, levels = 2) plot(country_level)
Region-level analysis
region_level <- rnsb(w = dictionary_demo, S_words = newsmap_europe, A_words = bing_pos, B_words = bing_neg, levels = 1) plot(region_level)
Comparison of the two effect sizes. Please note the much smaller effect size from region-level analysis. It reflects the evener distribution of P across regions than across countries.
calculate_es(country_level) calculate_es(region_level)
Normalized Association Score (Caliskan et al., 2017) is similar to Relative Norm Distance above. It was used in Müller et al. (2023).
S3 <- c("janitor", "statistician", "midwife", "bailiff", "auctioneer", "photographer", "geologist", "shoemaker", "athlete", "cashier", "dancer", "housekeeper", "accountant", "physicist", "gardener", "dentist", "weaver", "blacksmith", "psychologist", "supervisor", "mathematician", "surveyor", "tailor", "designer", "economist", "mechanic", "laborer", "postmaster", "broker", "chemist", "librarian", "attendant", "clerical", "musician", "porter", "scientist", "carpenter", "sailor", "instructor", "sheriff", "pilot", "inspector", "mason", "baker", "administrator", "architect", "collector", "operator", "surgeon", "driver", "painter", "conductor", "nurse", "cook", "engineer", "retired", "sales", "lawyer", "clergy", "physician", "farmer", "clerk", "manager", "guard", "artist", "smith", "official", "police", "doctor", "professor", "student", "judge", "teacher", "author", "secretary", "soldier") A3 <- c("he", "son", "his", "him", "father", "man", "boy", "himself", "male", "brother", "sons", "fathers", "men", "boys", "males", "brothers", "uncle", "uncles", "nephew", "nephews") B3 <- c("she", "daughter", "hers", "her", "mother", "woman", "girl", "herself", "female", "sister", "daughters", "mothers", "women", "girls", "females", "sisters", "aunt", "aunts", "niece", "nieces" ) nas_f1 <- query(googlenews, S_words= S3, A_words = A3, B_words = B3, method = "nas") plot(nas_f1)
There is a very strong correlation between NAS and RND.
cor.test(nas_f1$P, garg_f1$P)
This example reproduces the detection of "Math. vs Arts" gender bias in Caliskan et al (2017).
data(glove_math) # a subset of the original GLoVE word vectors S4 <- c("math", "algebra", "geometry", "calculus", "equations", "computation", "numbers", "addition") T4 <- c("poetry", "art", "dance", "literature", "novel", "symphony", "drama", "sculpture") A4 <- c("male", "man", "boy", "brother", "he", "him", "his", "son") B4 <- c("female", "woman", "girl", "sister", "she", "her", "hers", "daughter") sw <- query(glove_math, S4, T4, A4, B4) # extraction of effect size sw
By default, the effect size from the function weat_es
is adjusted by the pooled standard deviaion (see Page 2 of Caliskan et al. 2007). The standardized effect size can be interpreted the way as Cohen's d (Cohen, 1988).
One can also get the unstandardized version (aka. test statistic in the original paper):
## weat_es calculate_es(sw, standardize = FALSE)
The original implementation assumes equal size of S
and T
. This assumption can be relaxed by pooling the standard deviaion with sample size adjustment. The function weat_es
does it when S
and T
are of different length.
Also, the effect size can be converted to point-biserial correlation (mathematically equivalent to the Pearson's product moment correlation).
weat_es(sw, r = TRUE)
The exact test described in Caliskan et al. (2017) is also available. But it takes a long time to calculate.
## Don't do it. It takes a long time and is almost always significant. weat_exact(sw)
Instead, please use the resampling approximation of the exact test. The p-value is very close to the reported 0.018.
weat_resampling(sw)
Contributions in the form of feedback, comments, code, and bug report are welcome.
Please note that the sweater project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.
[^legacy]: Please use the query
function. These functions are kept for backward compatibility.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.