Algorithm Search⌘K

Algorithmadvanced

Word embedding association test

Also called WEAT.

Measure bias in embeddings by the difference of mean cosine similarities of two target word sets to two attribute sets, with a permutation test.

Time
O(n a d + n 4^n) exactO(n a d + m n) sampled
Space
O(n) extra
Where
a = the total size of the two attribute sets; d = the dimension of the vectors; m = the number of sampled partitions; n = the size of each target set
Properties
deterministicexactofflineiterativenot supervised
Origin
Aylin Caliskan, Joanna J. Bryson, Arvind Narayanan, 2017

The word embedding association test (WEAT) measures whether a set of word vectors puts one group of target words closer to one group of attribute words than another group of target words. For example, it asks whether flower names lie closer to pleasant words, and insect names closer to unpleasant words, than the other way around. It gives a test statistic, an effect size and a one-sided p-value from a permutation test over the ways to split the target words into two groups. The p-value is exact when all splits are listed; what the test says about bias in people or in applications is a matter of interpretation, not of the algorithm.

In plain words

Psychologists measure hidden associations with a timed test: people sort words faster when two concepts that they link in their minds share a response key. WEAT does the same with distances. Each target word, such as "rose" or "ant", gets a score: how much closer it is to the pleasant words than to the unpleasant words, on average. The test adds the scores of the flowers and takes away the scores of the insects. A big result means that the two target groups differ in their links to the two attribute groups.

To know whether the result is just chance, the test mixes the flowers and the insects, splits them into two new groups at random, and computes the same number. If few random splits give a number as large as the real one, the link is unlikely to be chance.

The problem

The input is four sets of vectors: two target sets XX and YY with nn words each, and two attribute sets AA and BB. The association of one word ww with the attributes is

s(w,A,B)=1∣A∣∑a∈Acos⁡(w,a)−1∣B∣∑b∈Bcos⁡(w,b),s(w, A, B) = \frac{1}{|A|} \sum_{a \in A} \cos(w, a) - \frac{1}{|B|} \sum_{b \in B} \cos(w, b),

with the cosine similarity. The test statistic is

s(X,Y,A,B)=∑x∈Xs(x,A,B)−∑y∈Ys(y,A,B).s(X, Y, A, B) = \sum_{x \in X} s(x, A, B) - \sum_{y \in Y} s(y, A, B).

The effect size is

d=mean⁡x∈Xs(x,A,B)−mean⁡y∈Ys(y,A,B)std⁡w∈X∪Ys(w,A,B).d = \frac{\operatorname{mean}_{x \in X} s(x, A, B) - \operatorname{mean}_{y \in Y} s(y, A, B)}{\operatorname{std}_{w \in X \cup Y} s(w, A, B)}.

Let (Xi,Yi)(X_i, Y_i) range over the (2nn)\binom{2n}{n} splits of X∪YX \cup Y into two sets of nn words. The one-sided p-value of the paper is p=Pr⁡i[s(Xi,Yi,A,B)>s(X,Y,A,B)]p = \Pr_i[s(X_i, Y_i, A, B) > s(X, Y, A, B)]. The output is the triple of the statistic, dd and pp.

The algorithm

  1. WEAT(X, Y, A, B)
  2. 1s_w ← s(w, A, B) for each w in X ∪ Y, with the n words of X first
  3. 2T ← Σ_w s_w
  4. 3S ← 2 Σ_{x ∈ X} s_x - T ▷ the statistic s(X, Y, A, B)
  5. 4σ ← standard deviation of the 2n values s_w
  6. 5d ← (mean of s_x over X - mean of s_y over Y) / σ
  7. 6count ← 0
  8. 7for each set X_i of n positions out of the 2n do
  9. 8S_i ← 2 Σ_{w ∈ X_i} s_w - T ▷ the statistic of the split (X_i, Y_i)
  10. 9if S_i > S then count ← count + 1
  11. 10(the loop visits C(2n, n) splits)
  12. 11return S, d, count / C(2n, n)

The associations do not depend on the split, so line L1 computes them once. Line L8 uses the identity ∑Yisw=T−∑Xisw\sum_{Y_i} s_w = T - \sum_{X_i} s_w, so each split costs O(n)O(n) and no cosine is computed again. When (2nn)\binom{2n}{n} is too large to list, the code draws mm random splits with a seeded generator and returns the fraction above SS. For the 25 flowers and 25 insects of the paper, (5025)\binom{50}{25} is about 1.3×10141.3 \times 10^{14}, so sampling is the only option there.

Example

The vectors below are written for this page, in two dimensions. Let A={(1,0)}A = \{(1, 0)\} be the pleasant attribute and B={(0,1)}B = \{(0, 1)\} the unpleasant one, so s(w,A,B)=(w1−w2)/∥w∥s(w, A, B) = (w_1 - w_2) / \|w\|.

set word vector s(w,A,B)s(w, A, B)
X (4, 1) 0.7276
X (3, 2) 0.2774
X (1, 3) -0.6325
Y (2, 3) -0.2774
Y (1, 4) -0.7276
Y (0, 1) -1.0000

The statistic is 0.3725−(−2.0050)=2.37750.3725 - (-2.0050) = 2.3775. The means are 0.12420.1242 and −0.6683-0.6683, and the population standard deviation of the six values is 0.60120.6012, so d=0.7925/0.6012=1.3182d = 0.7925 / 0.6012 = 1.3182 (with the sample standard deviation, d=1.2034d = 1.2034). There are (63)=20\binom{6}{3} = 20 splits. Only one gives a larger statistic: the split that swaps (1,3)(1, 3) with (2,3)(2, 3), with 3.08773.0877. So p=1/20=0.05p = 1/20 = 0.05. With "≥\ge" in line L9 the observed split also counts and p=2/20=0.1p = 2/20 = 0.1.

Correctness

Three exact statements hold, and the proof below gives them. First, line L8 computes the statistic of each split, since s(Xi,Yi,A,B)=2∑Xisw−Ts(X_i, Y_i, A, B) = 2\sum_{X_i} s_w - T. Second, the loop of line L7 visits every split once, so line L11 returns the p-value of the definition exactly. The fraction is the same over the (2n)!(2n)! orders of the words, since each split comes from n! n!n! \, n! orders. Third, with the population standard deviation, ∣d∣≤2|d| \le 2, with equality only when the associations are constant inside XX and inside YY. This follows from the variance decomposition σ2=(σX2+σY2)/2+((mX−mY)/2)2\sigma^2 = (\sigma_X^2 + \sigma_Y^2)/2 + ((m_X - m_Y)/2)^2. The draft of the paper notes that the largest effect size is 2.

The p-value is valid as a permutation test: if, under the null hypothesis, the labels X and Y fall on the 2n2n words as a uniform random split, then the "≥\ge" form gives Pr⁡[p≤α]≤α\Pr[p \le \alpha] \le \alpha. The strict form of the paper is never larger, so it rejects a little more often. The null hypothesis is about the given vectors with the given word lists. It is not a statement about a population of words, and the choice of the lists is not random.

Proof: WEAT computes the exact permutation p-value, and its effect size is at most 2full

We use the pseudocode of the page. The target sets XX and YY have n≥1n \ge 1 vectors each, AA and BB are nonempty, and every vector is nonzero. Write sw=s(w,A,B)s_w = s(w, A, B) for w∈X∪Yw \in X \cup Y, which line L1 computes, and T=∑w∈X∪YswT = \sum_{w \in X \cup Y} s_w (line L2). We treat X∪YX \cup Y as a list of 2n2n positions, so a word that occurs twice counts twice.

Lemma 1 (the partition identity). For every split of the 2n2n positions into XiX_i and YiY_i with ∣Xi∣=n|X_i| = n, s(Xi,Yi,A,B)=2∑w∈Xisw−Ts(X_i, Y_i, A, B) = 2 \sum_{w \in X_i} s_w - T.

Proof. s(Xi,Yi,A,B)=∑Xisw−∑Yisws(X_i, Y_i, A, B) = \sum_{X_i} s_w - \sum_{Y_i} s_w, and ∑Yisw=T−∑Xisw\sum_{Y_i} s_w = T - \sum_{X_i} s_w. □\square

So line L3 computes the statistic S=s(X,Y,A,B)S = s(X, Y, A, B) and line L8 the statistic of each split.

Theorem 1 (the p-value). Line L11 returns p=∣{Xi:s(Xi,Yi,A,B)>S}∣/(2nn)p = |\{X_i : s(X_i, Y_i, A, B) > S\}| / \binom{2n}{n}, the p-value of Caliskan, Bryson and Narayanan 2017. It is also the fraction of the (2n)!(2n)! orders of the 2n2n positions for which the first nn positions give a statistic larger than SS.

Proof. Line L7 visits each subset of nn of the 2n2n positions exactly once, so the loop runs (2nn)\binom{2n}{n} times and line L10 counts them. By Lemma 1, line L9 adds 1 exactly for the subsets whose statistic is larger than SS. For the second statement, each subset of size nn is the set of the first nn positions of exactly n! n!n! \, n! orders, the same number for every subset, so the two fractions are equal. □\square

With "≥\ge" in line L9 (strict = False in the code), the observed split itself counts, so the p-value is at least 1/(2nn)1 / \binom{2n}{n}. For n=4n = 4 this is 1/701/70, and for n=8n = 8 it is 1/128701/12870.

Theorem 2 (validity). Suppose that, under the null hypothesis, the labels XX and YY are given to the 2n2n fixed vectors by a uniform random choice of the nn positions called XX. Then the version with "≥\ge" satisfies Pr⁡[p≤α]≤α\Pr[p \le \alpha] \le \alpha for every α∈[0,1]\alpha \in [0, 1]. The version with ">>" is never larger, so it can only reject more often.

Proof. Let v1≥v2≥⋯≥vKv_1 \ge v_2 \ge \cdots \ge v_K be the statistics of the K=(2nn)K = \binom{2n}{n} splits. Under the null, the observed statistic SS is vJv_J for a uniform random index JJ. The "≥\ge" p-value of the split jj is pj=∣{k:vk≥vj}∣/Kp_j = |\{k : v_k \ge v_j\}| / K, which is at least j/Kj / K. So pJ≤αp_J \le \alpha implies J≤αKJ \le \alpha K, and Pr⁡[J≤αK]≤α\Pr[J \le \alpha K] \le \alpha. The strict version counts a subset of the same splits. □\square

Theorem 3 (the effect size). Let mXm_X and mYm_Y be the means of sws_w over XX and YY, and let σ\sigma be the population standard deviation of the 2n2n values sws_w (ddof = 0, line L4). If σ>0\sigma > 0, then ∣d∣=∣mX−mY∣/σ≤2|d| = |m_X - m_Y| / \sigma \le 2, with equality if and only if sws_w is constant on XX and constant on YY. With the sample standard deviation (ddof = 1), ∣d∣<2|d| < 2.

Proof. Let σX2\sigma_X^2 and σY2\sigma_Y^2 be the population variances inside XX and inside YY. The two sets have the same size, so the overall mean is (mX+mY)/2(m_X + m_Y)/2, and the decomposition of the variance into a within part and a between part gives

σ2=σX2+σY22+(mX−mY2)2≥(mX−mY2)2.\sigma^2 = \frac{\sigma_X^2 + \sigma_Y^2}{2} + \left(\frac{m_X - m_Y}{2}\right)^2 \ge \left(\frac{m_X - m_Y}{2}\right)^2.

Take square roots: ∣mX−mY∣≤2σ|m_X - m_Y| \le 2 \sigma. Equality holds if and only if σX=σY=0\sigma_X = \sigma_Y = 0. The sample standard deviation is σ2n/(2n−1)>σ\sigma \sqrt{2n / (2n - 1)} > \sigma, so the bound becomes strict. □\square

Symmetry. Swapping XX and YY, or AA and BB, changes the sign of every sws_w or of every label, so it negates SS and dd. The multiset of split statistics is symmetric about 0, since the splits (Xi,Yi)(X_i, Y_i) and (Yi,Xi)(Y_i, X_i) have opposite values. So the p-value for (Y,X)(Y, X) is the share of splits below SS, and the two one-sided p-values add up to 1 minus the share of splits whose statistic equals SS. ■\blacksquare

Complexity

The model is the real-RAM.

  • Associations. Line L1 computes 2n⋅a2n \cdot a cosines of dimension dd: O(nad)O(n a d) time.
  • Exact p-value. Lines L7 to L10 visit (2nn)\binom{2n}{n} splits at O(n)O(n) each. For n=8n = 8 that is 12,870 splits, and (2nn)\binom{2n}{n} grows like 4n/πn4^n / \sqrt{\pi n}, which gives the bound O(n4n)O(n 4^n) of the front matter.
  • Sampled p-value. O(mn)O(m n) for mm splits. The standard error of the estimate is about p(1−p)/m\sqrt{p(1 - p)/m}.
  • Space. O(n)O(n) beyond the input, for the 2n2n associations.

Properties

  • Exact test. For small sets the p-value is exact, with no assumption on the distribution of the associations.
  • Resolution. With "≥\ge" the smallest p-value is 1/(2nn)1/\binom{2n}{n}: 1/701/70 for n=4n = 4 and 1/128701/12870 for n=8n = 8. With the strict test of the paper the observed split never counts, so p=0p = 0 is possible.
  • Sign. Swapping XX and YY, or AA and BB, negates the statistic and dd.
  • Scale. Cosines ignore the length of the vectors, so the test does too.
  • Bounded effect size. ∣d∣≤2|d| \le 2, as above. The paper reports effect sizes and p-values, not only p-values, since a large nn makes small differences significant.

Variants and improvements

  • WEFAT. The word embedding factual association test of the same paper uses one target set and correlates s(w,A,B)s(w, A, B) with a real statistic of each word, such as the share of women in an occupation.
  • SEAT. May et al. 2019 put the words into simple sentence templates, such as "This is a rose.", and run the test on the vectors of sentence encoders. See sentence embedding and contextual word embedding.
  • Sampled test. Random splits replace the full list for large nn. Adding 1 to the count and to the number of splits makes the sampled p-value valid in the same sense as the exact one.
  • Bootstrap intervals. A bootstrap over the words of the lists gives an interval for dd. It shows how much the result depends on the particular words.

When to use it

Use WEAT to report whether a given embedding encodes a stated association, for example after a debiasing step. Gonen and Goldberg 2019 used it after hard debiasing and still measured p-values below 0.05 in all three of the gender tests they ran. Report the word lists, the embedding, the effect size and the p-value together. The test does not tell how a downstream system behaves; that needs a test of the system itself.

Pitfalls

  • Unequal target sets. The definition and the identity of line L8 assume ∣X∣=∣Y∣|X| = |Y|. The code raises an error for unequal sizes rather than give a number with another meaning.
  • Words missing from the vocabulary. Dropping the missing words of one list changes the test. Report the final lists.
  • Standard deviation. The paper does not state which of the two forms it uses. The population form gives the bound 2; the sample form gives a smaller value for the same data. Say which one you use.
  • Multiple tests. Running many WEATs and reporting the significant ones inflates the false positives. Correct for the number of tests.
  • Strict and non-strict tests. With ">>" and a small nn, p=0p = 0 can appear, which reads as stronger evidence than the data allow. The "≥\ge" form never goes below 1/(2nn)1/\binom{2n}{n}.
  • Word frequency. Rare words have noisier vectors, and names in particular differ in frequency. A large effect can come from frequency rather than from meaning.

Implementations

The code takes the word vectors as given and implements the association, the statistic, the effect size, the exact p-value over all splits and a sampled p-value with a seeded generator.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

weat_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-embedding-association-test/. The authors are listed in prov/R1EFZ2.jsonl.
"""The Word Embedding Association Test (WEAT) of Caliskan, Bryson and Narayanan 2017.

X and Y are two equal-size sets of target word vectors (for example flowers
and insects), and A and B are two sets of attribute word vectors (for example
pleasant and unpleasant words). The test returns the statistic s(X, Y, A, B),
the effect size d and the one-sided permutation p-value over the equal-size
partitions of X u Y. The vectors are given; the code does not train them.
"""

import math
import random
from itertools import combinations
from typing import List, Optional, Sequence, Tuple

Vector = Sequence[float]


def cosine(a: Vector, b: Vector) -> float:
    """The cosine a.b / (|a| |b|). Raise ValueError for a zero vector."""
    ab = math.fsum(x * y for x, y in zip(a, b))
    na = math.sqrt(math.fsum(x * x for x in a))
    nb = math.sqrt(math.fsum(y * y for y in b))
    if na == 0 or nb == 0:
        raise ValueError("the cosine of a zero vector is not defined")
    return ab / (na * nb)


def association(w: Vector, A: Sequence[Vector], B: Sequence[Vector]) -> float:
    """s(w, A, B): the mean cosine of w with A minus the mean cosine of w with B."""
    if not A or not B:
        raise ValueError("A and B must not be empty")
    return math.fsum(cosine(w, a) for a in A) / len(A) - math.fsum(cosine(w, b) for b in B) / len(B)


def _check_targets(X: Sequence[Vector], Y: Sequence[Vector]) -> None:
    if not X or len(X) != len(Y):
        raise ValueError("X and Y must be nonempty and of the same size")


def weat_statistic(X: Sequence[Vector], Y: Sequence[Vector], A: Sequence[Vector], B: Sequence[Vector]) -> float:
    """s(X, Y, A, B) = sum over x of s(x, A, B) minus sum over y of s(y, A, B)."""
    _check_targets(X, Y)
    return math.fsum(association(x, A, B) for x in X) - math.fsum(association(y, A, B) for y in Y)


def _std(values: List[float], ddof: int) -> float:
    m = math.fsum(values) / len(values)
    return math.sqrt(math.fsum((v - m) ** 2 for v in values) / (len(values) - ddof))


def effect_size(
    X: Sequence[Vector], Y: Sequence[Vector], A: Sequence[Vector], B: Sequence[Vector], ddof: int = 0
) -> float:
    """d = (mean over X of s - mean over Y of s) / std over X u Y of s.

    ddof = 0 divides the variance by |X u Y| (the population form, for which
    |d| <= 2), and ddof = 1 by |X u Y| - 1. Raise ValueError if every s is equal.
    """
    _check_targets(X, Y)
    sx = [association(x, A, B) for x in X]
    sy = [association(y, A, B) for y in Y]
    sd = _std(sx + sy, ddof)
    if sd == 0:
        raise ValueError("every association is equal, so the effect size is not defined")
    return (math.fsum(sx) / len(sx) - math.fsum(sy) / len(sy)) / sd


def weat(
    X: Sequence[Vector],
    Y: Sequence[Vector],
    A: Sequence[Vector],
    B: Sequence[Vector],
    ddof: int = 0,
    strict: bool = True,
) -> Tuple[float, float, float]:
    """Return (statistic, effect size, exact p-value).

    The p-value is the fraction of the C(2n, n) equal-size partitions (Xi, Yi)
    of X u Y with s(Xi, Yi, A, B) > s(X, Y, A, B), as in the paper. With
    strict = False the test uses >=, which counts the observed partition and
    so gives a p-value of at least 1 / C(2n, n).
    """
    _check_targets(X, Y)
    n = len(X)
    s = [association(w, A, B) for w in list(X) + list(Y)]  # @line L1
    total = math.fsum(s)  # @line L2
    observed = 2 * math.fsum(s[:n]) - total  # @line L3
    sd = _std(s, ddof)  # @line L4
    if sd == 0:
        raise ValueError("every association is equal, so the effect size is not defined")
    d = (math.fsum(s[:n]) / n - math.fsum(s[n:]) / n) / sd  # @line L5
    count = 0  # @line L6
    partitions = 0
    for xi in combinations(range(2 * n), n):  # @line L7
        si = 2 * math.fsum(s[k] for k in xi) - total  # @line L8
        if si > observed or (not strict and si == observed):  # @line L9
            count += 1
        partitions += 1  # @line L10
    return observed, d, count / partitions  # @line L11


def sampled_p_value(
    X: Sequence[Vector],
    Y: Sequence[Vector],
    A: Sequence[Vector],
    B: Sequence[Vector],
    samples: int,
    rng: Optional[random.Random] = None,
    strict: bool = True,
) -> float:
    """Estimate the p-value of weat from random equal-size partitions.

    Use it when C(2n, n) is too large to list. The estimate has a standard
    error of about sqrt(p (1 - p) / samples).
    """
    _check_targets(X, Y)
    if samples < 1:
        raise ValueError("samples must be positive")
    rng = rng or random.Random(0)
    n = len(X)
    s = [association(w, A, B) for w in list(X) + list(Y)]
    total = math.fsum(s)
    observed = 2 * math.fsum(s[:n]) - total
    idx = list(range(2 * n))
    count = 0
    for _ in range(samples):
        rng.shuffle(idx)
        si = 2 * math.fsum(s[k] for k in idx[:n]) - total
        if si > observed or (not strict and si == observed):
            count += 1
    return count / samples
test_word_embedding_association_test.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-embedding-association-test/. The authors are listed in prov/R1EFZ2.jsonl.

import math
import random
from itertools import permutations

import pytest

from word_embedding_association_test import (
    association,
    effect_size,
    sampled_p_value,
    weat,
    weat_statistic,
)

A = [[1.0, 0.0]]
B = [[0.0, 1.0]]
X = [[4.0, 1.0], [3.0, 2.0], [1.0, 3.0]]
Y = [[2.0, 3.0], [1.0, 4.0], [0.0, 1.0]]


def rand_vec(rng, d):
    return [rng.gauss(0.0, 1.0) for _ in range(d)]


def planted(rng, n, d, direction, shift):
    return [[x + shift * u for x, u in zip(rand_vec(rng, d), direction)] for _ in range(n)]


def test_association_hand_values():
    assert association([4.0, 1.0], A, B) == pytest.approx(3 / math.sqrt(17))
    assert association([1.0, 1.0], A, B) == pytest.approx(0.0)
    assert association([0.0, 1.0], A, B) == pytest.approx(-1.0)
    two = [[1.0, 0.0], [0.0, 2.0]]
    # The mean over A of the cosines with (1, 1) is 1 / sqrt(2), and B gives -1 / sqrt(2).
    assert association([1.0, 1.0], two, [[-1.0, 0.0]]) == pytest.approx(math.sqrt(2))


def test_page_example():
    stat, d, p = weat(X, Y, A, B)
    assert stat == pytest.approx(2.3775, abs=1e-4)
    assert d == pytest.approx(1.3182, abs=1e-4)
    assert p == pytest.approx(1 / 20)
    assert weat(X, Y, A, B, strict=False)[2] == pytest.approx(2 / 20)
    assert effect_size(X, Y, A, B, ddof=1) == pytest.approx(1.2034, abs=1e-4)
    assert weat_statistic(X, Y, A, B) == pytest.approx(stat, abs=1e-12)
    assert effect_size(X, Y, A, B) == pytest.approx(d, abs=1e-12)


def test_exact_p_value_equals_the_fraction_over_all_permutations():
    rng = random.Random(1)
    for _ in range(5):
        Xs = [rand_vec(rng, 4) for _ in range(3)]
        Ys = [rand_vec(rng, 4) for _ in range(3)]
        As = [rand_vec(rng, 4) for _ in range(2)]
        Bs = [rand_vec(rng, 4) for _ in range(3)]
        words = Xs + Ys
        obs = weat_statistic(Xs, Ys, As, Bs)
        greater = 0
        total = 0
        for perm in permutations(range(6)):
            xi = [words[k] for k in perm[:3]]
            yi = [words[k] for k in perm[3:]]
            if weat_statistic(xi, yi, As, Bs) > obs + 1e-12:
                greater += 1
            total += 1
        assert total == 720
        assert weat(Xs, Ys, As, Bs)[2] == pytest.approx(greater / total)


def test_sampled_p_value_is_close_to_the_exact_one():
    rng = random.Random(2)
    direction = [1.0, 0.0, 0.0, 0.0]
    Xs = planted(rng, 5, 4, direction, 0.4)
    Ys = planted(rng, 5, 4, direction, -0.4)
    As = planted(rng, 4, 4, direction, 1.0)
    Bs = planted(rng, 4, 4, direction, -1.0)
    exact = weat(Xs, Ys, As, Bs)[2]
    est = sampled_p_value(Xs, Ys, As, Bs, 4000, random.Random(3))
    assert abs(est - exact) < 0.03


def test_effect_size_is_at_most_two():
    rng = random.Random(4)
    for _ in range(200):
        n = rng.randint(2, 5)
        Xs = [rand_vec(rng, 3) for _ in range(n)]
        Ys = [rand_vec(rng, 3) for _ in range(n)]
        As = [rand_vec(rng, 3) for _ in range(2)]
        Bs = [rand_vec(rng, 3) for _ in range(2)]
        assert abs(effect_size(Xs, Ys, As, Bs)) <= 2 + 1e-12
        assert abs(effect_size(Xs, Ys, As, Bs, ddof=1)) <= 2 + 1e-12


def test_effect_size_reaches_two_when_each_set_is_constant():
    Xs = [[1.0, 0.0], [2.0, 0.0], [5.0, 0.0]]
    Ys = [[0.0, 1.0], [0.0, 3.0], [0.0, 0.5]]
    assert effect_size(Xs, Ys, A, B) == pytest.approx(2.0)
    assert effect_size(Ys, Xs, A, B) == pytest.approx(-2.0)


def test_swaps_negate_the_statistic_and_the_effect_size():
    rng = random.Random(5)
    Xs = [rand_vec(rng, 3) for _ in range(4)]
    Ys = [rand_vec(rng, 3) for _ in range(4)]
    As = [rand_vec(rng, 3) for _ in range(3)]
    Bs = [rand_vec(rng, 3) for _ in range(3)]
    s, d, p = weat(Xs, Ys, As, Bs)
    s2, d2, p2 = weat(Ys, Xs, As, Bs)
    s3, d3, _ = weat(Xs, Ys, Bs, As)
    assert s2 == pytest.approx(-s) and s3 == pytest.approx(-s)
    assert d2 == pytest.approx(-d) and d3 == pytest.approx(-d)
    # The partition values are symmetric about 0, so p2 is the share of values
    # below s, and p + p2 + (the share of values equal to s) = 1.
    ties = weat(Xs, Ys, As, Bs, strict=False)[2] - p
    assert p + p2 + ties == pytest.approx(1.0)


def test_smallest_p_value():
    Xs = [[1.0, 0.0], [1.0, 0.1], [1.0, 0.2], [1.0, 0.3]]
    Ys = [[0.0, 1.0], [0.1, 1.0], [0.2, 1.0], [0.3, 1.0]]
    assert weat(Xs, Ys, A, B)[2] == 0.0
    assert weat(Xs, Ys, A, B, strict=False)[2] == pytest.approx(1 / 70)


def test_planted_bias_gives_a_small_p_value_and_none_gives_a_large_one():
    rng = random.Random(6)
    direction = [1.0, 0.0, 0.0, 0.0, 0.0]
    As = planted(rng, 4, 5, direction, 2.0)
    Bs = planted(rng, 4, 5, direction, -2.0)
    Xs = planted(rng, 6, 5, direction, 1.5)
    Ys = planted(rng, 6, 5, direction, -1.5)
    _, d, p = weat(Xs, Ys, As, Bs)
    assert d > 1.0 and p < 0.01
    flat = [rand_vec(rng, 5) for _ in range(12)]
    p_null = [weat(flat[:6], flat[6:], As, Bs)[2], weat(flat[6:], flat[:6], As, Bs)[2]]
    assert max(p_null) > 0.05


def test_bad_input():
    with pytest.raises(ValueError):
        weat([[1.0, 0.0]], [], A, B)
    with pytest.raises(ValueError):
        association([1.0, 0.0], [], B)
    with pytest.raises(ValueError):
        effect_size([[1.0, 0.0]], [[2.0, 0.0]], A, B)
    with pytest.raises(ValueError):
        sampled_p_value(X, Y, A, B, 0)
word_embedding_association_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-embedding-association-test/. The authors are listed in prov/R1EFZ2.jsonl.
"""Entry point named after the slug. The code lives in weat_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from weat_core import association, cosine, effect_size, sampled_p_value, weat, weat_statistic

__all__ = ["association", "cosine", "effect_size", "sampled_p_value", "weat", "weat_statistic"]

History

Greenwald, McGhee and Schwartz 1998 introduced the Implicit Association Test, which measures associations through the reaction times of people. Caliskan, Bryson and Narayanan 2017 replaced the reaction times with cosine similarities and replicated the classic tests on GloVe vectors trained on 840 billion tokens of Common Crawl text (2.2 million words, 300 dimensions). In their measurements, flowers against insects with pleasant and unpleasant words gave d=1.50d = 1.50 with p<10−7p < 10^{-7}, musical instruments against weapons gave d=1.53d = 1.53 with p<10−7p < 10^{-7}, and male against female names with career and family words gave d=1.81d = 1.81 with p<10−3p < 10^{-3}. These are measurements on one embedding. The test then became a standard measure of bias in embeddings and was extended to sentence encoders.

References

  1. Aylin Caliskan, Joanna J. Bryson and Arvind Narayanan, Semantics derived automatically from language corpora contain human-like biases, Science 356(6334), 2017, pages 183 to 186, the methods section that defines s(w, A, B), the test statistic, the permutation p-value and the effect size, and the table of the replicated tests
  2. Anthony G. Greenwald, Debbie E. McGhee and Jordan L. K. Schwartz, Measuring individual differences in implicit cognition, the implicit association test, Journal of Personality and Social Psychology 74(6), 1998, the flower and insect, instrument and weapon, and other tests that WEAT replicates
  3. Hila Gonen and Yoav Goldberg, Lipstick on a pig, debiasing methods cover up systematic gender biases in word embeddings but do not remove them, NAACL-HLT 2019, pages 609 to 614, the WEAT p-values of the embeddings after hard debiasing
  4. May et al. 2019, SEAT, the extension of WEAT to sentence encoders

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.exact
  • a full proof of time.sampled
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example