File size: 30,042 Bytes
228c64a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
"""Generate semantic_axis_gender.ipynb (run once; then execute the notebook)."""
import nbformat as nbf

cells = []
md = lambda s: cells.append(nbf.v4.new_markdown_cell(s.strip("\n")))
code = lambda s: cells.append(nbf.v4.new_code_cell(s.strip("\n")))

# ═══════════════════════════════════════════════════════════════════════════
md(r"""
# Are words gendered? Semantic axes, word embeddings and *The Guardian* (1999–2026)

This notebook asks a simple question: **when The Guardian writes about a man or a woman, does it use different words?** It also asks whether that has changed over 25 years.

We will:

1. look at **what the data is**: words attached to male and female characters;
2. learn how **word embeddings** (fastText) put words in a geometric space;
3. use them to build a **semantic axis** (e.g. *brutal ↔ gentle*) or a **semantic category** (e.g. *cognition verbs*) from a handful of seed words;
4. measure whether that axis or category is **male- or female-skewed**, and **how this changes over time**.

> **For students.** Every section ends with something you can change: seed words, slot, pooling. The functions are short and documented, so read them!
""")

md(r"""
## 0. Where the data comes from

Each Guardian article (1999–2026) was processed with **BookNLP**, a pipeline that:

1. finds **characters**, i.e. people mentioned in the text (*Theresa May*, *she*, *the prime minister*…);
2. groups the mentions that refer to the same person (**coreference**);
3. assigns a **gender** to each character, from pronouns (*he/she*), honorifics (*Mr/Mrs*) and first names. Characters with contradictory cues are dropped;
4. collects the words **syntactically attached** to each character, in four **slots**:

| slot | what it is | example: *"Angry, she **attacked** her **rival**, who was later **sacked**"* |
|---|---|---|
| `agent` | verbs the character **does** | she → *attack* |
| `patient` | verbs **done to** the character | the rival → *sack* |
| `mod` | adjectives / nouns **describing** the character | she → *angry* |
| `poss` | nouns the character **possesses** | she → *rival* |

We then **count**, per year and slot, how often each word was attached to a man vs a woman. The output is a table of counts, with no text in it. This is the dataset [`regicid/guardian_attribute_counts`](https://huggingface.co/datasets/regicid/guardian_attribute_counts).
""")

code(r"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import normalize

pd.set_option("display.width", 140)

# --- a small, consistent visual vocabulary for the whole notebook --------
MALE, FEMALE = "#2a78d6", "#eb6834"          # men = blue, women = orange
SLOT_COLORS = {"agent": "#2a78d6", "patient": "#eb6834",
               "mod": "#1baf7a", "poss": "#eda100"}
plt.rcParams.update({
    "figure.figsize": (8, 4.5), "figure.dpi": 110,
    "axes.spines.top": False, "axes.spines.right": False,
    "axes.grid": True, "grid.color": "#e5e4e0", "grid.linewidth": .6,
    "axes.edgecolor": "#8a8984", "axes.labelcolor": "#52514e",
    "xtick.color": "#52514e", "ytick.color": "#52514e",
    "lines.linewidth": 2, "lines.markersize": 4, "legend.frameon": False,
})
""")

md(r"""
### 0.1 Loading the counts

The file has one row per `(year, slot, word)`. The `word` column is the raw token (*said*, *says*, *told*). The `lemma` column is its dictionary form (*say*, *say*, *tell*): this lets us count *says* and *said* as the same verb. See `lemmatize.py` on the dataset page for how this was done.
""")

code(r"""
URL = "hf://datasets/regicid/guardian_attribute_counts/attribute_counts_by_year.csv"
raw = pd.read_csv(URL, keep_default_na=False)   # keep_default_na: "null", "nan" are real words here
raw.sample(8, random_state=0)
""")

md(r"""
**From tokens to lemmas.** We sum the counts of all tokens that share a lemma. From now on, `word` means *lemma*.

We also compute, for each `(year, slot)`, the **total** number of male and female attributes (`male_slot_total`, `female_slot_total`). These are the denominators that we will compare everything against.
""")

code(r"""
attr = (raw.groupby(["corpus", "year", "slot", "lemma"], as_index=False)
           [["male_count", "female_count", "total"]].sum()
           .rename(columns={"lemma": "word"}))

slot_tot = (attr.groupby(["year", "slot"])[["male_count", "female_count"]].sum()
                .rename(columns={"male_count": "male_slot_total",
                                 "female_count": "female_slot_total"}))
attr = attr.merge(slot_tot, on=["year", "slot"])

print(f"{len(raw):,} token rows  ->  {len(attr):,} lemma rows")
attr[attr.word == "say"].head()
""")

# ═══════════════════════════════════════════════════════════════════════════
md(r"""
## 1. First look: who gets written about?

Before asking *how* women and men are described, we need to know *how often* they are. This **baseline** is crucial: if women make up 25% of all attributes, then a word attached to women 25% of the time is **not** female-skewed. It is exactly average.
""")

code(r"""
share = (attr.groupby(["year", "slot"])[["male_count", "female_count"]].sum()
             .assign(female_share=lambda d: d.female_count / (d.male_count + d.female_count))
             .reset_index())

fig, ax = plt.subplots()
for slot, g in share.groupby("slot"):
    ax.plot(g.year, g.female_share, marker="o", color=SLOT_COLORS[slot], label=slot)
    ax.annotate(slot, (g.year.iloc[-1] + .3, g.female_share.iloc[-1]),
                color="#52514e", va="center", fontsize=9)
ax.set_ylim(0, .5)
ax.yaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1))
ax.set_ylabel("share of attributes attached to women")
ax.set_title("Women's share of attributes, by slot")
ax.legend(title="slot", ncol=4, loc="upper left");
""")

md(r"""
**Things to notice**

* Women are a clear **minority** of the people the Guardian writes about, but their share **grows** over the period.
* The share **differs by slot**: women are relatively more often *possessors* or *patients* than *agents*. That is already a finding: see §1.2.
* 2026 is a **partial year**.

### 1.1 The most gendered words (no embeddings yet)

A simple way to rank words is the **log-odds ratio**: how much more likely is a word for a woman than for a man, *given* each gender's total? We pool all years and keep reasonably frequent words.
""")

code(r"""
def gendered_words(attr, slot, n=15, min_total=500, k=.5):
    # log OR > 0 = female-skewed, relative to the slot baseline
    d = attr[attr.slot == slot]
    w = d.groupby("word")[["male_count", "female_count"]].sum()
    M, F = d.drop_duplicates("year")[["male_slot_total", "female_slot_total"]].sum()
    w = w[w.sum(axis=1) >= min_total]
    w["log_or"] = (np.log((w.female_count + k) / (F - w.female_count + k))
                   - np.log((w.male_count + k) / (M - w.male_count + k)))
    w = w.sort_values("log_or")
    return pd.concat([w.head(n).assign(side="male"), w.tail(n).assign(side="female")])

g = gendered_words(attr, "mod")
fig, ax = plt.subplots(figsize=(7, 7))
ax.barh(g.index, g.log_or, color=np.where(g.log_or > 0, FEMALE, MALE), height=.7)
ax.axvline(0, color="#8a8984", lw=1)
ax.set_xlabel("log odds ratio   (← male-skewed   |   female-skewed →)")
ax.set_title("Most gendered modifiers (mod), 1999–2026");
""")

md(r"""
Some of these are **trivial** (*woman*, *actress*), because they are part of how gender was detected. Others are **interesting** (look at the *appearance* and *family* words).

You can try `gendered_words(attr, "agent")` or `"poss"`.

But word-by-word lists have two problems: (i) there are tens of thousands of words, and (ii) single words are noisy. We want to ask about **meanings**: *"are women described with more emotional words?"* For that we need to group words by meaning, which is what embeddings are for.

### 1.2 A first, embedding-free measure: agentivity

Are men more often **agents** (doing things) and women more often **patients** (having things done to them)? We build a **2×2 table** for each year:

|  | agent | patient |
|---|---|---|
| **men** | a | b |
| **women** | c | d |

The **odds ratio** OR = (a/b) / (c/d) is **> 1** if men are relatively more often agents. We'll reuse this 2×2 logic all the way through the notebook.
""")

code(r"""
def agentivity_or(attr, pool=1):
    # men-vs-women odds ratio of being agent rather than patient, per year
    t = attr.drop_duplicates(["year", "slot"])[["year", "slot", "male_slot_total", "female_slot_total"]].copy()
    t["year"] = t.year // pool * pool
    t = t.groupby(["year", "slot"]).sum().unstack("slot")
    a, b = t[("male_slot_total", "agent")],   t[("male_slot_total", "patient")]
    c, d = t[("female_slot_total", "agent")], t[("female_slot_total", "patient")]
    log_or = np.log(a) + np.log(d) - np.log(b) - np.log(c)
    se = np.sqrt(1/a + 1/b + 1/c + 1/d)
    return pd.DataFrame({"odds_ratio": np.exp(log_or), "log_or": log_or, "se": se}).reset_index()

ag = agentivity_or(attr)
fig, ax = plt.subplots()
ax.axhline(1, color="#8a8984", lw=1, ls="--")
ax.plot(ag.year, ag.odds_ratio, marker="o", color=MALE)
ax.fill_between(ag.year, np.exp(ag.log_or - 1.96*ag.se), np.exp(ag.log_or + 1.96*ag.se), color=MALE, alpha=.15, lw=0)
ax.set_ylabel("odds ratio (men vs women)")
ax.set_title("Agentivity: are men more often agents than patients?");
""")

# ═══════════════════════════════════════════════════════════════════════════
md(r"""
## 2. Word embeddings in five minutes

A **word embedding** maps each word to a vector (here 300 numbers) so that **words used in similar contexts get similar vectors**. *"You shall know a word by the company it keeps"* (Firth, 1957).

We use **fastText** (Bojanowski et al., 2017), trained by Facebook on Common Crawl, i.e. billions of words of web text. Two properties matter for us:

* it is **not trained on the Guardian**, so the geometry is "general English", not "Guardian English". This is a good thing: we don't want the embedding to have already absorbed the gender bias we are measuring *from the same corpus*;
* it builds vectors from **character n-grams**, so it can produce a vector for any word, even misspelled or rare ones.

**Similarity** between two words = **cosine** of the angle between their vectors (1 = same direction, 0 = unrelated).

#### Loading the vectors

* **Option A (full model, ~7 GB of RAM).** Download `cc.en.300.bin` with `fasttext.util.download_model('en')` and set `FT_PATH`.
* **Option B (light, for laptops).** We pre-computed the fastText vector of every lemma in the dataset (`fasttext_vectors.npz`, ~90 MB on the dataset page). This is enough for everything below, **as long as your seed words appear in the data**.

The code picks A if the file exists, and B otherwise.
""")

code(r"""
import os
FT_PATH = os.path.expanduser("~/Downloads/cc.en.300.bin")

if os.path.exists(FT_PATH):                                   # Option A
    import fasttext
    ft = fasttext.load_model(FT_PATH)
    vec = ft.get_word_vector
    print("full fastText model loaded")
else:                                                         # Option B
    from huggingface_hub import hf_hub_download
    z = np.load(hf_hub_download("regicid/guardian_attribute_counts",
                                "fasttext_vectors.npz", repo_type="dataset"))
    _index = {w: i for i, w in enumerate(z["words"])}
    _M = z["vectors"].astype(np.float32)
    def vec(w):
        i = _index.get(w)
        if i is None:
            print(f"  ! '{w}' not in the pre-computed vocabulary: ignored")
            return np.zeros(_M.shape[1], np.float32)
        return _M[i]
    print(f"pre-computed vectors loaded: {len(_index):,} words")


def embed(words):
    # one L2-normalised row per word: dot product = cosine similarity
    return normalize(np.array([vec(w) for w in words]))
""")

code(r"""
def cosine(w1, w2):
    a, b = embed([w1, w2])
    return float(a @ b)

for pair in [("angry", "furious"), ("angry", "happy"), ("angry", "table"),
             ("husband", "wife"), ("career", "job"), ("career", "baby")]:
    print(f"{pair[0]:>8} – {pair[1]:<8} {cosine(*pair):.2f}")
""")

md(r"""
Note that *angry–happy* is quite similar: **antonyms share contexts** (*"I am very ___"*). Embeddings capture *relatedness* more than *synonymy*. This is why we will build axes from **two contrasting poles**, rather than from one list of words.

Let's look at the **nearest neighbours** of a word, among the vocabulary of one slot:
""")

code(r"""
VOCAB = {s: (attr[attr.slot == s].groupby("word").total.sum()
             .loc[lambda x: x >= 20].index.to_list())          # words seen >= 20 times
         for s in attr.slot.unique()}
EMB = {s: embed(VOCAB[s]) for s in VOCAB}                        # cached: computed once

def neighbours(word, slot, n=12):
    sims = EMB[slot] @ embed([word])[0]
    top = np.argsort(-sims)[:n]
    return pd.Series(sims[top], index=np.array(VOCAB[slot])[top]).round(2)

neighbours("caress", "agent").to_frame("cosine").T
""")

# ═══════════════════════════════════════════════════════════════════════════
md(r"""
## 3. From seed words to a semantic axis

Suppose we want to study **brutality vs gentleness** in what characters *do* (agent verbs). We write down a few **seed words** for each pole:

* brutal pole: *attack, hit, smash, slam, crush, threaten, …*
* gentle pole: *caress, comfort, soothe, whisper, hug, …*

We then need a score for **every** verb in the data (thousands of them). There are two classic ways to get one.

### 3.1 Method 1: the centroid axis (SemAxis, An et al. 2018; Kozlowski et al. 2019)

1. average the vectors of each pole: $\bar v_+$ and $\bar v_-$;
2. the **axis** is the difference $a = \bar v_+ - \bar v_-$;
3. a word's score is its **projection** on the axis: $\text{score}(w) = \cos(w, a)$.

It is simple, transparent and has no parameters.

### 3.2 Method 2: a classifier (what we used for the French press)

Train a **logistic regression** to tell pole + from pole – using the 300 dimensions, then score every word by $P(+\mid w)$. The classifier learns **which dimensions matter**, which is often sharper than a plain average. It can also handle a **category** ("cognition verbs" vs *anything else*) when there is no natural opposite pole: then the negatives are random words.
""")

code(r"""
def semaxis(pos, neg, slot):
    # Method 1: projection on (centroid+ − centroid−); returns word, score
    a = embed(pos).mean(0) - embed(neg).mean(0)
    a /= np.linalg.norm(a)
    return pd.DataFrame({"word": VOCAB[slot], "score": EMB[slot] @ a})


def classify(pos, slot, neg=None, threshold=.8, seed=0):
    # Method 2: logistic regression pos vs neg (default: random vocabulary words).
    # Returns word, prob, category (= prob > threshold).
    if neg is None:      # a "category" rather than an axis: contrast with random words
        rng = np.random.default_rng(seed)
        neg = list(rng.choice([w for w in VOCAB[slot] if w not in pos], 3 * len(pos), replace=False))
    X, y = embed(pos + neg), np.r_[np.ones(len(pos)), np.zeros(len(neg))]
    clf = LogisticRegression(max_iter=1000, class_weight="balanced").fit(X, y)
    out = pd.DataFrame({"word": VOCAB[slot], "prob": clf.predict_proba(EMB[slot])[:, 1]})
    out["category"] = out.prob > threshold
    return out


def show_poles(scores, col, n=20):
    # the n words at each end of the axis: the first sanity check
    s = scores.sort_values(col)
    return pd.DataFrame({"← low end": s.word.head(n).values, "high end →": s.word.tail(n).values[::-1]})
""")

code(r"""
brutal = ["attack", "hit", "smash", "slam", "crush", "batter", "threaten", "punch",
          "bully", "intimidate", "force", "dominate", "lash", "berate", "storm", "thump"]
gentle = ["caress", "comfort", "soothe", "console", "whisper", "hug", "cuddle", "nurture",
          "reassure", "embrace", "murmur", "stroke", "tend", "cradle", "smile", "thank"]

ax_brut = semaxis(brutal, gentle, "agent")
show_poles(ax_brut, "score")
""")

md(r"""
**Always read the poles before you trust an axis.** Does the top look brutal, and the bottom gentle? If you see words that don't belong, think about why. They may be polysemous (*strike* = hit, or go on strike), or they may share contexts with the seeds without sharing meaning. Then refine the seeds.

The same axis with the classifier:
""")

code(r"""
clf_brut = classify(brutal, "agent", neg=gentle, threshold=.5)
show_poles(clf_brut, "prob")
""")

code(r"""
# Do the two methods agree? (rank correlation over all agent verbs)
m = ax_brut.merge(clf_brut, on="word")
print("Spearman ρ =", round(m.score.corr(m.prob, method="spearman"), 2))
""")

# ═══════════════════════════════════════════════════════════════════════════
md(r"""
## 4. Is the axis gendered? Two measures

We now have a score for each word. Each word also has a male count and a female count. There are two ways to combine them.

### 4.1 Continuous: the standardized mean difference (SMD)

Take **every attribute token** attached to a man and average its axis score; do the same for women. The difference, divided by the overall standard deviation, is Cohen's **d**:

$$ d = \frac{\bar s_{\text{men}} - \bar s_{\text{women}}}{\sigma} $$

* $d>0$: men's words sit **further toward the + pole** (here: brutal).
* $d = 0.1$ means the two distributions are shifted by a tenth of a standard deviation. That is small in psychology terms, but it is a *systematic* shift across millions of tokens.

This uses **all** words, weighted by how often they occur. It does not need a threshold.
""")

code(r"""
def weighted_axis_smd(attr, scores, col="score", slots=None, pool=1, min_tokens=30, logit=False, eps=1e-6):
    # Male-minus-female gap on a continuous axis, in SD units (Cohen's d).
    # scores: DataFrame with `word` and a score column `col`.
    # logit:  if the score is a probability, un-bunch it with log(p/(1-p)).
    # The SD is computed once, on all years, so it is a fixed ruler over time.
    d = attr[attr.slot.isin(slots)] if slots else attr
    sc = scores[["word", col]].rename(columns={col: "s"})
    if logit:
        p = sc.s.clip(eps, 1 - eps); sc["s"] = np.log(p / (1 - p))
    d = d.merge(sc, on="word")

    N = d.male_count + d.female_count
    sbar = np.average(d.s, weights=N)
    sigma = np.sqrt(np.average((d.s - sbar) ** 2, weights=N))
    d = d.assign(year=d.year // pool * pool)

    def stats(g):
        wM, wF, s = g.male_count.values, g.female_count.values, g.s.values
        if wM.sum() < min_tokens or wF.sum() < min_tokens:
            return pd.Series(dict(d=np.nan, se=np.nan))
        muM, muF = np.average(s, weights=wM), np.average(s, weights=wF)
        vM, vF = np.average((s - muM)**2, weights=wM), np.average((s - muF)**2, weights=wF)
        nM, nF = wM.sum()**2 / (wM**2).sum(), wF.sum()**2 / (wF**2).sum()  # Kish effective N:
        se = np.sqrt(vM/nM + vF/nF) / sigma                                # a few frequent words ≠ many tokens
        return pd.Series(dict(d=(muM - muF) / sigma, se=se))

    return d.groupby("year").apply(stats, include_groups=False).reset_index()


def plot_skew(o, y="d", log_band=False, ax=None, label=None, color="#52514e",
              ylabel="d  (men − women, SD units)", title=None, ref=0):
    # One time series with a 95% band. Above `ref` = male-skewed, below = female-skewed.
    if ax is None:
        _, ax = plt.subplots()
    o = o.dropna(subset=[y]).sort_values("year")
    if log_band:   # odds ratios: the band is symmetric on the log scale
        lo, hi = np.exp(o.log_or - 1.96 * o.se), np.exp(o.log_or + 1.96 * o.se)
    else:
        lo, hi = o[y] - 1.96 * o.se, o[y] + 1.96 * o.se
    ax.axhline(ref, color="#8a8984", lw=1, ls="--", zorder=0)
    ax.plot(o.year, o[y], marker="o", color=color, label=label)
    ax.fill_between(o.year, lo, hi, color=color, alpha=.15, lw=0)
    ax.text(1.01, .98, "male-skewed ↑", transform=ax.transAxes, color=MALE, fontsize=8, va="top")
    ax.text(1.01, .02, "female-skewed ↓", transform=ax.transAxes, color=FEMALE, fontsize=8, va="bottom")
    ax.set_ylabel(ylabel); ax.set_title(title)
    return ax
""")

code(r"""
smd = weighted_axis_smd(attr, ax_brut, slots=["agent"])
plot_skew(smd, title="Brutal ↔ gentle verbs (agent): gap between men and women");
""")

md(r"""
### 4.2 Categorical: the odds ratio of a lexicon

Sometimes we want to talk about a **category** (*"physical-appearance adjectives"*) rather than a position on an axis. Then:

1. turn the scores into a **lexicon** (words with `prob > threshold`, or the top-k of an axis), and **read it**;
2. for each year, the 2×2 table:

|  | words in the lexicon | all other words of the slot |
|---|---|---|
| **men** | a | b |
| **women** | c | d |

3. **OR = (a/b)/(c/d)**. OR = 2 means *the odds that a man's modifier is a lexicon word are twice a woman's*. OR = 0.5 means the reverse.

Because we compare with each gender's **own total**, the result does not depend on women being written about less often.
""")

code(r"""
def lexicon_or(attr, lex, slots=None, pool=1, k=.5, max_se=.25):
    # Men-vs-women odds ratio of using a word from `lex`, per (pooled) year.
    # k: Haldane–Anscombe correction (avoids log 0). Points with se > max_se are dropped.
    d = attr[attr.slot.isin(slots)] if slots else attr
    d = d.assign(year=d.year // pool * pool)
    # one total per (year, slot) BEFORE pooling years, otherwise we'd drop some
    tot = (attr[attr.slot.isin(slots)] if slots else attr).drop_duplicates(["year", "slot"])
    tot = tot.assign(year=tot.year // pool * pool).groupby("year")[["male_slot_total", "female_slot_total"]].sum()
    hit = d[d.word.isin(set(lex))].groupby("year")[["male_count", "female_count"]].sum()
    o = tot.join(hit).fillna(0)
    a, c = o.male_count, o.female_count
    b, dd = o.male_slot_total - a, o.female_slot_total - c
    o["log_or"] = np.log(a + k) + np.log(dd + k) - np.log(b + k) - np.log(c + k)
    o["se"] = np.sqrt(1/(a+k) + 1/(b+k) + 1/(c+k) + 1/(dd+k))
    o.loc[o.se > max_se, "log_or"] = np.nan
    o["odds_ratio"] = np.exp(o.log_or)
    return o.reset_index()


def plot_or(o, **kw):
    # odds ratio on a log scale, 95% CI band; > 1 = male-skewed
    ax = plot_skew(o, y="odds_ratio", log_band=True,
                   ref=1, ylabel=kw.pop("ylabel", "odds ratio (men vs women, log scale)"), **kw)
    ax.set_yscale("log")
    ax.yaxis.set_major_formatter(plt.matplotlib.ticker.ScalarFormatter())
    ax.yaxis.set_minor_formatter(plt.matplotlib.ticker.NullFormatter())
    return ax


def drivers(attr, lex, slot, n=15):
    # Which lexicon words carry the effect? counts pooled over all years
    d = attr[(attr.slot == slot) & attr.word.isin(set(lex))].groupby("word")[["male_count", "female_count"]].sum()
    tot = attr[attr.slot == slot].drop_duplicates("year")[["male_slot_total", "female_slot_total"]].sum()
    d["per_10k_men"] = 1e4 * d.male_count / tot.male_slot_total
    d["per_10k_women"] = 1e4 * d.female_count / tot.female_slot_total
    d["ratio_w/m"] = d.per_10k_women / d.per_10k_men
    return d.sort_values("female_count", ascending=False).head(n).round(2)
""")

# ═══════════════════════════════════════════════════════════════════════════
md(r"""
## 5. Worked examples

### 5.1 A category: physical appearance (mod)
""")

code(r"""
physical = ["beautiful", "pretty", "ugly", "bald", "blonde", "brunette", "slim", "skinny",
            "fat", "chubby", "sexy", "gorgeous", "attractive", "handsome", "petite", "curvy",
            "bearded", "glamorous", "stunning", "slender", "muscular", "tanned", "busty", "lanky"]

phys = classify(physical, "mod", threshold=.6)
lex_phys = pd.Series(sorted(set(phys.loc[phys.category, "word"]) | set(physical)))  # seeds always in
print(len(lex_phys), "words in the lexicon:\n", ", ".join(lex_phys.sort_values()))
""")

md(r"""
👉 **Read the list.** The classifier extends the seeds to words we hadn't thought of, but it may also let in errors. If it does, raise the threshold or add those words as negatives (`neg=[...]`).
""")

code(r"""
o = lexicon_or(attr, lex_phys, slots=["mod"], pool=2)
plot_or(o, color=FEMALE, title="Physical-appearance modifiers: odds ratio men vs women (2-year bins)");
""")

code(r"""
drivers(attr, lex_phys, "mod")
""")

md(r"""
### 5.2 A category: cognition verbs (agent)

Do women *think*, *argue*, *analyse* as often as men in the news?
""")

code(r"""
cognition = ["think", "analyse", "argue", "reason", "predict", "estimate", "conclude",
             "consider", "reflect", "deduce", "assess", "calculate", "theorise", "evaluate",
             "ponder", "infer", "hypothesise", "speculate"]

cog = classify(cognition, "agent", threshold=.6)
lex_cog = pd.Series(sorted(set(cog.loc[cog.category, "word"]) | set(cognition)))
print(len(lex_cog), "words:", ", ".join(lex_cog.sort_values()))
plot_or(lexicon_or(attr, lex_cog, slots=["agent"]), color=MALE,
        title="Cognition verbs (agent): odds ratio men vs women");
""")

md(r"""
### 5.3 An axis: family ↔ career (poss)

What do men and women **have**, according to the Guardian? Here an axis is more natural than a category, because there are two poles. We show both measures.
""")

code(r"""
family = ["husband", "wife", "child", "daughter", "son", "baby", "mother", "father",
          "family", "home", "wedding", "marriage", "pregnancy", "kitchen", "grandchild"]
career = ["career", "job", "salary", "company", "office", "promotion", "colleague", "business",
          "boss", "contract", "employer", "profession", "employee", "client", "firm"]

ax_fc = semaxis(career, family, "poss")          # + pole = career
display(show_poles(ax_fc, "score", n=15))

fig, axes = plt.subplots(1, 2, figsize=(13, 4.5))
plot_skew(weighted_axis_smd(attr, ax_fc, slots=["poss"]), ax=axes[0],
          title="Family ↔ career (poss): SMD, + = men nearer career")
top = ax_fc.sort_values("score").word
plot_or(lexicon_or(attr, top.tail(300), slots=["poss"]), ax=axes[1], color=MALE,
        label="300 most 'career' nouns")
plot_or(lexicon_or(attr, top.head(300), slots=["poss"]), ax=axes[1], color=FEMALE,
        label="300 most 'family' nouns", title="…and as two lexicons (top-300 at each pole)")
axes[1].legend(loc="center left")
plt.tight_layout();
""")

md(r"""
### 5.4 One axis, all slots

The same axis can be computed in every slot where it makes sense. Here is the brutal ↔ gentle axis for what characters **do** (`agent`) and what is **done to them** (`patient`):
""")

code(r"""
fig, ax = plt.subplots()
for slot in ["agent", "patient"]:
    sc = semaxis(brutal, gentle, slot)
    plot_skew(weighted_axis_smd(attr, sc, slots=[slot], pool=2), ax=ax,
              color=SLOT_COLORS[slot], label=slot)
ax.legend(title="slot"); ax.set_title("Brutal ↔ gentle: men − women gap, agent vs patient (2-year bins)");
""")

md(r"""
---
## 6. Caveats

* **Seed words are a theory.** The axis is only as good as the seeds, so always show the poles and the lexicon. Try to break your own axis: swap a few seeds and check that the result holds.
* **Embedding bias.** fastText was trained on web text that is itself gendered. An axis like *strong ↔ weak* may partly encode gender in its own geometry. A useful check is to project *he / she / man / woman* on your axis.
* **Extraction errors.** BookNLP's parsing, coreference and gender detection are imperfect. Errors that are **constant over time** do not create trends, but errors that **differ by gender** can bias levels.
* **Lemmatization without context.** Lemmas were assigned to isolated words, so *left* is always *leave*, never the adjective. This is mostly harmless, but it's worth remembering for ambiguous words.
* **Composition.** A trend can come from **who** is written about (more female politicians, more sportswomen) rather than **how** they are written about. To separate the two, you would need finer metadata (sections, occupations).
* **Significance ≠ size.** With millions of tokens, everything is "significant". Look at the **magnitude** (d, OR) and at its **stability over time**.

## 7. Exercises

1. **Emotion.** Build an *emotional ↔ composed* axis on `mod` (*upset, tearful, emotional, hysterical, anxious, …* vs *calm, composed, measured, rational, …*). Is it gendered? Has it changed?
2. **Robustness.** Re-run 5.2 with `threshold=.5` and `.9`. Does the trend survive?
3. **Method.** For the family ↔ career axis, compare `semaxis` and `classify(career, "poss", neg=family)`. Where do they disagree?
4. **Your own axis.** Pick a dimension you care about (competence, morality, danger, sport, …), write 15 seeds per pole, and produce one SMD figure and one OR figure.
5. **Embedding bias.** Compute `embed(["he","she","man","woman"]) @ axis` for one of your axes (see `semaxis`). What does it tell you?
""")

nb = nbf.v4.new_notebook(cells=cells, metadata={
    "kernelspec": {"name": "python3", "display_name": "Python 3", "language": "python"},
    "language_info": {"name": "python"}})
nbf.write(nb, "semantic_axis_gender.ipynb")
print("written", len(cells), "cells")