⌂ 課程目錄
🐞 回報
English
互動功能初始化失敗,已改為「全部章節依序展開」的靜態版本,可直接往下捲動閱讀。(互動實驗室、測驗判分、進度與投影片對照需要 JavaScript;若在 App 內預覽看不到互動,請用「分享 → 以 Safari 打開」或在電腦瀏覽器開啟。)
00 · 本週導覽

W9:詞嵌入與政治語言(Word Embeddings and Political Language)

W8 的主題模型回答「大家在談什麼、談多少」。W9 換一個問題:同一個字在不同人、不同時期嘴裡是不是用法不一樣?做法是把字(或字的每一次出現)變成一串從語料學來的數字——向量(vector),再用 cosine 比較方向。本週有四個政治學案例、一個 Flair 小 Lab、一個 conText(embedding regression)Lab。

開場問題:security 在說什麼? 投影片 2

投影片 2 用 security 起頭:同一個字會出現在國防(Security Council)、能源(energy security)、經濟(social security)三種語境。老師拋出兩個問題:哪些鄰近的字幫我們分辨這些用法?以及怎麼檢驗這些用法在政黨或時期之間有沒有差異?整週就是在回答這兩題。

白話翻譯(補充)

想像你只能從「一個字旁邊常出現哪些字」來猜它的意思。security 旁邊出現 council、nations,大概是聯合國;出現 social、benefits,大概是社福。詞嵌入就是把這種「旁邊都是誰」的資訊壓成一串數字。本週後半的 embedding regression 再更進一步:每一次出現都給一個向量,才能比較民主黨和共和黨怎麼用同一個字。

本週要能說明的事 投影片 77、92

整理自投影片 77 的 Lab 目標(「向量代表什麼、怎麼比較、怎麼檢查詮釋」)與投影片 92 的研究設計三步驟。讀完一章後回來勾選:

  1. 向量代表什麼:分清楚「一個字型(word type)一個向量」(靜態 GloVe)與「一次出現(occurrence)一個向量」(ALC/conText)。
  2. 怎麼比較:會算、會讀 cosine;知道 PCA 2D 圖上的距離不等於全維度的 cosine。
  3. 四個案例:每個研究「什麼拿到向量、比較什麼、用什麼證據支撐政治詮釋」。
  4. conText 結果:解釋 party_R 在「固定 gender」下比較什麼,並用一個鄰居字和一段 context 支撐。
  5. 設計自己的研究:寫一段話說明問題、單位、語料、表示法、比較方式與會改變結論的證據。

課堂路線(110 分鐘) 投影片 16、77、80

依 W9/README.md:全套 112 張,主講 1–94,補充 95–112;Lab 30 分鐘(17:40–18:10)。點每一段看重點:

→ → → → →
段落投影片問題(README 原文意譯)
概念與研究地圖1–16向量代表什麼?怎麼學出來?
Case 1 · Rheault & Cochrane17–26議會語言能不能定位政黨?
Case 2 · Rodman27–36字詞關聯能不能揭露概念變遷?
Case 3 · Müller & Proksch37–46鄰居字怎麼幫忙建立並驗證懷舊量測?
Case 4 · Embedding regression47–71怎麼比較不同群體對同一個字的用法?
多語資源與應用72–76這個方法還用在哪裡?
Lab 導覽與休息77–80Lab 要比較什麼?
Flair 與 PCA81–85載入 GloVe、取得向量、比較 security、讀投影圖
conText86–91建 context 向量、讀鄰居與段落、固定 gender 比較政黨
研究設計與參考文獻92–94什麼證據能支持我們自己的比較?
補充95–112額外概念、情緒量測、評估、可讀性

四個案例一覽 投影片 16、109

案例文本什麼拿到向量怎麼回答問題
1 · Rheault & Cochrane (2020)議會發言一個政黨在一屆議會(party-term)PC1 給出發言量尺,用 Voteview 解讀
2 · Rodman (2020)NYT 中標題含 equality 的新聞一個字在一個歷史時期cosine 追蹤關聯,新聞段落說明改變了什麼
3 · Müller & Proksch (2024)歐洲政黨黨綱種子字與候選字鄰居擴充字典,分數進回歸
4 · Rodriguez, Spirling & Stewart (2023)美國國會紀錄目標字的每一次出現回歸估計差距,鄰居和段落解釋差距

表格整理自投影片 16(案例與文本)與投影片 109(Four ways embeddings support an answer)。

怎麼使用本教材

  • 右側「投影片對照」會跟著段落切到對應頁;每個 投影片 N 標籤都可以點。
  • R 程式碼與輸出全部是本機實跑(R 4.5.3(aarch64-conda-linux-gnu)、quanteda 4.5.1、quanteda.textstats 0.97.2);Flair 用 Python 路線實跑(Python 3.11.2、flair 0.15.1、torch 2.5.1、numpy 1.26.4、gensim 4.4.0)。每個數字都對過投影片,對不上的地方會兩邊並列。
  • 標「補充(非講義內容)」的是我加的白話說明或玩具示範,不是老師的投影片內容。

本章小測驗

1. W9 和 W8 主題模型相比,要回答的核心問題是?
投影片 3:W8 問 “What do actors discuss, and how much?”;W9 問 “How can learned vectors describe and compare political language?” 投影片 3
2. 在 Case 4(embedding regression),什麼拿到一個向量?
投影片 109 第 4 列:“One use of a target word”。Case 1 才是 party-term,Case 2 是 word × period。投影片 109
3. 本週 Lab 的 30 分鐘怎麼分?
投影片 80:“Our 2024 Flair exercise and plots (15 min) → conText Quick Start (15 min)”。投影片 80
01 · 向量直覺

從 one-hot 到詞嵌入:視窗、CBOW/Skip-gram、cosine

one-hot 的問題:每個不同的字 cosine 都是 0 投影片 3–6

投影片 3–6(依 Hung-yi Lee 教學圖與 Grimmer, Roberts & Stewart 2022 第 8 章 p. 78):one-hot 給每個字一個專屬座標,所以 dog 和 cat 的向量完全不重疊,cosine = 0,看不出它們很像。詞嵌入改成「從用法學來的座標」,dog、cat、rabbit 出現在相似語境時就會靠近。

互動:one-hot vs 嵌入(補充(非講義內容),玩具數字)

嵌入座標是我自己編的 3 維玩具值,只為了示範「one-hot 全是 0、嵌入有遠近」;真實模型是 30、100 或 300 維。

上下文視窗:c = 1 與 c = 2 投影片 7–10

投影片 7(Text as Data §8.2.4, p. 83)用 “The cute cat jumps over …” 示範:視窗 c = 1 時 cat 的上下文是 cute 和 jumps;c = 2 時再加上 The 和 over。CBOW(Continuous Bag of Words)由上下文預測 cat;Skip-gram 由 cat 預測上下文。學好之後用 cosine 比較向量的方向。

互動:拖動視窗大小、點一個字當目標(補充(非講義內容))

cosine 計算機 投影片 101

投影片 101(Schoonvelde 2026, ESS Day 3 的數字例子):Defence 演說的計數是 (security=1, forces=1, energy=0),Energy 演說是 (1, 0, 1)。

cos(a, b) = a·b / (‖a‖‖b‖) = 1 / (√2·√2) = 0.50

互動:改數字看 cosine(預設值=投影片 101)
securityforcesenergy
Defence (a)
Energy (b)
為什麼用 cosine 而不是距離?(補充)

cosine 只看方向、不看長度。把 Defence 演說每個計數都乘 10(變成很長的演說),cosine 仍是 0.50——試試看把上面 a 列改成 10, 10, 0。

用預測學座標 投影片 95–99

補充投影片 95–98:輸入是一個詞彙位置(one-hot),中間是學到的座標 z1、z2,輸出是下一個字的機率(目標 attends);預測錯誤會更新連線權重。學完後留下的中間層權重就是詞向量。投影片 99(GRS 2022 §8.1, p. 80)的影評例子說明為什麼這有用:訓練資料裡有 great,新影評用 fantastic;如果兩個字向量相近,分類器能把學到的東西「帶過去」。

本章小測驗

1. 視窗 c = 2、目標字 cat,句子 “The cute cat jumps over …”,上下文是?
c = 1 是 cute、jumps;c = 2 再加 The、over。投影片 7
2. CBOW 和 Skip-gram 的差別?
投影片 7、11:CBOW: context → word;Skip-gram: word → context。投影片 7、11
3. 投影片 101 兩篇演說的 cosine 是 0.50。若把 Defence 的計數都乘 10,cosine 變成?
cosine 只看方向。分子分母同乘 10,比值不變。(補充推論,可用上面的計算機驗證。)
02 · 訓練選擇

訓練選擇決定你拿到哪種向量

四種方法、兩種表示 投影片 11–15

方法或介面學習訊號表示
Word2VecCBOW:context → word;Skip-gram:word → context靜態詞向量
GloVe(Global Vectors for Word Representation)擬合整個語料的共現統計靜態詞向量
fastText用字元 n-gram 從上下文預測靜態詞向量
FlairEmbeddings字元語言模型使用周圍文字情境化(contextual)token 向量

投影片 11 的 Lab 選擇:用 Flair 的 WordEmbeddings("glove") 載入靜態 GloVe。注意:Flair 這個套件也能做情境化向量(FlairEmbeddings),但本週 Lab 用的是它包裝的靜態 GloVe——所以 ch08 的三個 security 向量會一模一樣。

容易搞混

「用 Flair」≠「用情境化向量」。WordEmbeddings("glove") 是查表:同一個字型永遠回傳同一列。投影片 11、84

每一列代表什麼? 投影片 100

投影片 100(Schoonvelde 2026, ESS Day 3, p. 6):文件計數矩陣每一列是一篇演說的特徵計數;靜態詞嵌入每一列是一個字型學到的座標。比較兩篇演說 → 比 DFM 的兩列;比較兩個字 → 比嵌入矩陣的兩列。

把字向量平均成文件向量 投影片 102

投影片 102(GRS 2022 §8.3, pp. 86–87):逐座標平均。第一個 token (1, 0)、第二個 (0, 2),文件平均 (0.5, 1.0)。重複出現的字會重複貢獻。W9.R 的 R06 就是這樣做文件向量(ch10)。

互動:平均計算器(預設=投影片 102)

翻牌卡:靜態還是情境化?

本章小測驗

1. 投影片 11 的表格中,哪一個產生「情境化 token 向量」?
只有 FlairEmbeddings 標 Contextual token vector。投影片 11
2. fastText 和 Word2Vec 最大的差別是?
投影片 11:fastText “Predict from context with character n-grams.” 共現統計是 GloVe。投影片 11
3. 文件有 3 個 token:(1,0)、(0,2)、(1,0)。簡單平均是?
(1+0+1)/3 = 0.67、(0+2+0)/3 = 0.67。重複的 token 重複貢獻。投影片 102
03 · Case 1

Case 1 · Rheault & Cochrane (2020):從議會發言定位政黨

問題與資料 投影片 17

背景:記名表決(roll-call votes)是定位政黨的一種方法。問題:發言能不能也揭露政黨位置,以及位置在各屆之間怎麼變?文本:美國、英國、加拿大的議會辯論;模型為每個政黨在每一屆學一個向量。(Political Analysis 28(1): 112–133)

怎麼用嵌入:Predict → Represent → Project 投影片 18–20

  1. Predict:模型從上下文加上 party-term 標籤預測字(例子是 work)。
  2. Represent:每個 party-term 得到一個向量,例如 Labour 2005。
  3. Project:用 PCA 把所有 party-term 向量投影,在 PC1 上比較。

來源:投影片 18 引作者 preprint Figure 1, p. 8。

讀圖:PC1 隨年份 投影片 21–23

橫軸是年份、縱軸是 PC1(party-term 向量變異最大的方向)。1920 年附近兩黨差距小(民主黨藍色虛線、共和黨紅色實線);到 2000 年兩黨在這個發言量尺上遠得多。(作者 preprint Figure 2b, p. 15)

在模型之外驗證 投影片 24–26

美國眾議院(1921–2016)數字
發言 PC1 與 Voteview 政黨平均的相關0.918
party-term 配對排序一致率85.66%

結論:在這段重疊期間可以把 PC1 讀成左右量尺;但一致程度隨基準而不同。(作者 preprint Table 2, p. 20)

為什麼要外部驗證?(補充)

PCA 只保證 PC1 是「變異最大的方向」,不保證它是意識形態——也可能是年代、議題或議事程序。拿獨立的 Voteview 來比,才有理由叫它 left–right。這和 W7 Wordfish 的道理一樣。

本章小測驗

1. Rheault & Cochrane 中,什麼拿到向量?
“The model represents each party in each legislative term.” 投影片 17
2. 0.918 是什麼?
U.S. House:Speech-based PC1 correlates 0.918 with Voteview party averages (1921–2016)。投影片 24
3. 主張判斷:「PC1 是變異最大的方向,所以它一定是左右意識形態。」
投影片 24:“We can read PC1 as a left–right scale in this overlapping period. Agreement varies across benchmarks.” 投影片 24
04 · Case 2

Case 2 · Rodman (2020):equality 的意思怎麼變

問題與資料 投影片 27

背景:equality 這個字一直存在,但圍繞它的辯論一直在變。問題:不同年代,哪些群體與議題和 equality 連在一起?文本:NYT Article API 中標題含 equality 的 3,105 則新聞,1855–2016。(Political Analysis 28(1): 87–111)

新聞語境變成歷史證據 投影片 28–30

研究步驟Rodman 怎麼做
收集語境用標題、摘要和(若有)第一段;把新聞分成七個年代。
估計嵌入比較四種 Word2Vec 訓練方案,每種都產生各年代的詞向量。
追蹤關聯在每個年代內算 equality 與選定字的 cosine,再跨年代追蹤。

投影片 28 引作者手稿 §§5.2, 5.4。

選模型:哪個最接近人工編碼? 投影片 31–33

讀欄位:偏差(deviation)越低、與基準的相關越高越好。chronological 那一列相關最高(0.611)、偏差最低,最接近五個人工編碼的主題趨勢。Rodman 接著用它追蹤新的字對。(作者手稿 Table 2, p. 25)

這一步的意義(補充)

四種訓練方案都「能跑」,但只有拿人工編碼當基準,才知道哪個最可信。這是 ch11 會講的 substantive/extrinsic 評估:不是看向量漂不漂亮,而是看它能不能重現人類判斷。

讀 social–equality 曲線 投影片 34–36

互動:逐步讀圖(數字取自投影片 34/36,作者手稿 Figure 4, p. 29)
投影片 34 的討論題

「回升到 .30,是否表示早期用法還在?」投影片 36 的答案是:要回去讀段落。同樣的 cosine 可以來自完全不同的用法。

本章小測驗

1. Rodman 的語料是?
投影片 27
2. Rodman 怎麼選出 chronological 模型?
投影片 31
3. 主張判斷:「social–equality 的 cosine 從 .19 回升到 .30,證明 19 世紀的用法延續到今天。」
投影片 36
05 · Case 3

Case 3 · Müller & Proksch (2024):用鄰居字建懷舊字典

問題與資料 投影片 37

背景:提到過去可以是讚美、批評或懷舊。問題:文化保守的政黨是不是更常訴諸「更好的過去」?文本:24 個歐洲國家、1,648 份黨綱,1946–2018。(BJPS 54(3): 993–1005;本篇是 W10 選讀,W9 拿來當案例。)

從鄰居字到懷舊量測 投影片 38–40

  1. 找候選字:在預訓練 GloVe 和用黨綱訓練的向量中,搜尋種子字的鄰居。
  2. 篩選:三位編碼者審查鄰居字;通過的字組成 embeddings-based 字典。
  3. 計分:結合兩本字典;每 1,000 句被標記的句數成為比較政黨的結果變數。

投影片 38 引 Figure 1 panels 1–2, p. 996;Supplement §B.2。

互動:當一次篩選編碼者(補充(非講義內容))

下面是「如果種子字是 tradition」時嵌入可能給的鄰居類型(我編的示範字,不是論文的字表)。勾選你會留進懷舊字典的字,再看提示。

先驗證量測,再比較政黨 投影片 41–43

他們比較字典(M1–M4)和句子分類器(M5–M6)的黨綱分數,用 50 份黨綱對照兩位編碼者:

方法與編碼者的一致(投影片數字)
基礎字典(base).61
擴充字典(expanded,加入嵌入鄰居).54
SVM(句子分類器).87
DistilBERT(句子分類器).86
重點:擴充後一致性反而下降

投影片 43:“We see lower agreement after expansion.” 嵌入鄰居增加了覆蓋,但也帶進雜訊。擴充字典不保證更好,要驗證。(Figure 2, p. 998;句子驗證 p. 997)

跨六種量測比較政黨 投影片 44–46

六個標準化懷舊分數當欄位;M2 用擴充字典、M4 另外要求正面情感。框起來的那一列:M2 是 .08、M4 是 .07。文化保守量尺每高一分,黨綱懷舊高 .07–.10 個標準差(六個模型、控制其他變數)。(Table 1, p. 1001;文化保守量尺見 Supplement §C.6)

本章小測驗

1. 在 Müller & Proksch,嵌入的角色是?
投影片 38、109
2. 擴充字典(.54)和基礎字典(.61)比,代表什麼?
投影片 43
3. 「.07–.10」怎麼讀?
投影片 44
06 · Case 4 直覺

Case 4 直覺:同一個字、不同語境 → ALC → 回歸

chips:英國薯條、美國洋芋片 投影片 47–49

同一個字 chips:英國用法旁邊有 ketchup、knife and fork(熱薯條);美國用法旁邊有 a bag(洋芋片)。這裡的「意思」就是使用模式。(投影片註明是構造的例子;Embedding Regression Non-Technical Explainer §1)

一個語境變成一個 ALC 向量 投影片 50–53

  1. 查表:在同一個預訓練空間裡查語境字的向量。
  2. 平均:ui = (1/|Ci|) Σw∈Ci vw(這一次出現周圍的字)。
  3. 校準:yi = A ui;A 是學到的線性轉換,修正「平均」造成的偏差。

一次使用 → 一個向量。同一個字的不同用法,可以在同一空間裡拿到不同表示。

為什麼需要 A?(補充,依 RSS 2023 p. 1259)

直接平均語境字向量時,常見字(像 the、and)會把所有平均都拉向同一個方向。Khodak et al. (2018) 的 à la carte 方法學一個矩陣 A,讓「語境平均經 A 轉換後」盡量接近該字原本的預訓練向量。conText 的 cr_transform 就是配合 cr_glove_subset 學好的 A——所以投影片一直強調 E 和 A 必須是 matched pair。

ALC 玩具計算機(補充(非講義內容))

互動:選語境字 → 平均 → 乘上 A → 看離哪個意思近

2 維玩具空間(數字是我編的):x 軸≈「熱食/餐具」,y 軸≈「包裝零食」。勾選這一次 chips 出現時旁邊的字:

context 向量就是回歸的結果變數 投影片 54–57

觀察值 = chips 的一次使用;結果 = 它的 D 維 context 向量。

yi = β0 + UKi βUK + εi (UKi:US = 0、UK = 1)

兩個係數都是 D 維向量。讀結果:用係數長度(norm)看差異大小,再用鄰居字和段落解釋差異內容;用置換(permutation)評估不確定性。下一步把英語變體換成政黨,研究 immigration。(Explainer §§3–5)

白話(補充)

一般回歸的 y 是一個數字;這裡 y 是一整排 300 個數字,等於同時跑 300 條回歸、共用同一組 X。βUK 這一排數字說的是:「英國的用法平均往哪個方向偏」。它的長度就是「偏多少」。

conText:從語境到回歸 投影片 59–62

步驟內容
1 · 一次出現一列保留語境、party、gender。n 次使用 → n × D 結果矩陣 Y。
2 · 建結果向量平均語境字向量(排除目標字),再套共同的 ALC 轉換:ui = mean vw,yi = A ui。
3 · 對所有座標回歸yi = α + Ri βR + Mi βM + εi(R:共和黨;M:男性);α、βR、βM 各有 D 個元素。
4 · 讀係數α 是民主黨/女性參照組;βR 是固定 gender 下的政黨比較。畫長度,並組合係數得到各組的鄰居字。

投影片 59 引 RSS (2023) pp. 1258–1259, 1264–1266 與官方 Quick Start。toks:文字+metadata;E 與 A:一組配對。

本章小測驗

1. ALC 的第三步「校準」是?
投影片 50
2. 在 yi = β0 + UKiβUK + εi 中,βUK 是什麼?
“Both coefficients are D-coordinate vectors… we use coefficient length for the size of the difference.” 投影片 54
3. 為什麼 E(預訓練向量)和 A(轉換矩陣)必須配對?
投影片 59:“E and A: a matched pair.” 也見 README:conText 例子有自己的 300 維向量與相配的 ALC 轉換。投影片 59、86
07 · Case 4 結果

Case 4 結果:immigration、多語擴充與其他應用

問題與資料 投影片 58

背景:兩黨提到 immigration 的次數可能一樣多,但用的語境不同。問題:同一個字的用法怎麼隨政黨和性別而變?文本:美國國會紀錄(Congressional Record)第 111–114 屆。(APSR 117(4): 1255–1274,W9 核心閱讀)

比較政黨與性別差異的長度 投影片 63–65

高度=調整後差異向量的長度:0 表示沒有向量差異,越大差異越大;誤差線是 95% bootstrap 區間。immigration:政黨 .175(固定性別)、性別 .087(固定政黨)。三個政治詞的政黨差距都比較大。(Figure 5;Supplement Table J.4)

互動:論文長度 vs 本週 Lab 的數字(不要混在一起比)

左:論文 Figure 5/Table J.4 的 L2 長度(投影片 63)。右:本機重跑 Quick Start 的 normed.estimate.deflated(去偏後的平方長度,投影片 91)。兩組單位不同、資料規模也不同(Lab 只有 400 篇樣本),只能各自比較「政黨 > 性別」這個方向。

群體差異裡有什麼?鄰居字 投影片 66–68

每一列是和該黨估計的 immigration 向量 cosine 最近的十個字。框起來的部分:民主黨附近是改變制度(changing the system),共和黨附近是執行現行法律(enforcing existing law);enact、legislation 兩列都有。(Table 4, p. 1267)

回到原始段落 投影片 69–71

讀和各黨估計向量最近的段落:民主黨的段落談 reform、共和黨的段落談 enforcement。範圍限制:這些段落只是說明對比;要估計某種用法多常見,需要更廣的樣本。(Table 5, p. 1267)

英文以外:多語嵌入 投影片 72

Wirsching et al. (2025, Political Analysis, Figure 1, p. 159) 在每個語言內比較 ALC 估計和預訓練向量。依 W9/reading/README.md:這個檢查不代表跨語言對齊;非英文研究可以用該語言自己的模型,但不要跨語言比座標。

延伸提示(補充)

如果要做中文(例如立法院質詢),流程一樣:中文預訓練向量 E+針對它學的 A。conText 的 Quick Start 只附英文 cr_glove_subset/cr_transform,中文要另找配對資源(Wirsching et al. 2025 提供 157 種語言)。

四個 embedding regression 應用 投影片 73–76

研究比較
Gonthier (2025) · SPSR不同意識形態群體怎麼用法文 peuple
Van Matre et al. (2026) · PSJ氣候框架 × 政黨 × 國會屆次
Karell & Sachs (2023) · Socius政治訊號(Trump 回歸 Twitter)前後的少數群體語言
Kim & Kesari (2021) · JOTS“Chinese virus”:仇恨/反仇恨 × 時間

本章小測驗

1. 論文中 immigration 的政黨差異長度(固定性別)是?
.175 是論文 Figure 5;.087 是性別;8.668 是本週 Lab 的去偏平方長度,單位不同。投影片 63、91
2. 為什麼看完 β 的長度還要看鄰居字和段落?
投影片 54、66、69
3. 主張判斷:「Table 5 的民主黨段落談 reform,所以多數民主黨議員談 immigration 時都談 reform。」
“These passages illustrate the contrast. To estimate frequency, we need a broader sample.” 投影片 69
08 · Lab A:Flair

Lab A(17:40–17:55):Flair 載入靜態 GloVe、比較 security、讀 PCA

F00:課前準備環境與模型 投影片 81

投影片 81:課前用 Lab F00 準備好 Python、套件和 GloVe;從課程根目錄 source("W9/lab/flair/flair_prepare.R")(R 路線要 reticulate+flaiR),R 不行就改 Python 路線。安裝與下載都在課前完成。

本機怎麼跑的(照實說)

這台是 2 GB 記憶體的 Linux 容器,沒有 flaiR/reticulate,所以我走 Python 路線:另建乾淨 venv,照 W9/lab/flair/requirements.txt 裝 flair[word-embeddings]==0.15.1、numpy < 2(Python 3.11.2、flair 0.15.1、torch 2.5.1、numpy 1.26.4、gensim 4.4.0)。第一次 WordEmbeddings('glove') 下載約 20.5 MB 模型到 ~/.flair/embeddings/glove.gensim,載入時峰值 RSS 約 1237 MB。R 路線(flaiR)沒有在本機跑;老師的 runtime.json 記錄 R 與 Python 向量差在 1e-6 以內。

課前準備建議(補充)

在自己的 Mac 上:python3.11 -m venv .venv && .venv/bin/pip install -r W9/lab/flair/requirements.txt,再跑 .venv/bin/python W9/lab/flair/flair_lab.py --download-glove 預載模型、--check 檢查。看到 “Imports OK. Device: CPU.” 就過關。

三步驟:載入 → 11 × 100 → 3 × 100 投影片 82–84

課堂用的是 R 版 flair_steps.R(三段和 Python 版一一對應):

W9/lab/flair/flair_steps.R
# W9 Flair: run these three sections after sourcing flair_prepare.R.
# Keep the same R session. PCA remains in the separate after-class exercise.

# ==== Step 1: Load the model ====
embedding <- WordEmbeddings(glove_path)
print(embedding$embedding_length)

# ==== Step 2: Get word vectors ====
word_list <- paste("King Queen man woman Paris London",
  "apple orange Taiwan Dublin Bamberg")
word_sentence <- Sentence(word_list)
embedding$embed(word_sentence)
word_vectors <- do.call(rbind, lapply(word_sentence$tokens,
  function(token) as.numeric(token$embedding$tolist())))
print(dim(word_vectors))

# ==== Step 3: Compare security ====
security_texts <- c("Social security supports households.",
  "The United Nations Security Council met.",
  "Energy security matters for jobs.")
sentences <- lapply(security_texts, Sentence)
embedding$embed(sentences)
security_vectors <- do.call(rbind, lapply(sentences, function(sentence) {
  token <- Filter(function(t) tolower(t$text) == "security",
    sentence$tokens)[[1]]
  as.numeric(token$embedding$tolist())
}))
print(dim(security_vectors))
unit <- security_vectors / sqrt(rowSums(security_vectors ^ 2))
security_cosine <- tcrossprod(unit)
print(round(security_cosine, 6))

本機實跑 Python 版 flair_steps.py(先 import flair_prepare.py)的完整輸出:

Python 輸出(本機實跑:Python 3.11.2、flair 0.15.1、torch 2.5.1、numpy 1.26.4、gensim 4.4.0)
$ python flair_steps.py
Python 3.11.2 at …/env/flair/bin/python
flair 0.15.1
torch 2.5.1
numpy 1.26.4
matplotlib 3.11.2
gensim 4.4.0
Imports OK. Device: CPU.
Cached model file: ~/.flair/embeddings/glove.gensim
Ready for Step 1: load the model.
100
(11, 100)
(3, 100)
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
檢查點投影片本機
embedding_length100(投影片 82)100 ✓
11 個字的矩陣11 × 100(投影片 83)(11, 100) ✓
三句 security3 × 100,兩兩 cosine 1(投影片 84)(3, 100)、全為 1 ✓
為什麼三個 security 一模一樣?

Social security、Security Council、Energy security 三種完全不同的用法,靜態查表回傳同一個字型向量,所以 cosine = 1。這正是 Case 4 要解決的問題:靜態向量把一個字所有用法混在一起。(注意 GloVe 先轉小寫,Security 和 security 查到同一列。)投影片 84

11 × 11 全維度 cosine(本機 flair_lab.py --run 實跑) 投影片 83、85

互動:點一格看那一對的 cosine;點字名看它的排序

數字和老師 repo 的 W9/lab/flair/example-output/word-cosine.csv 到小數第 4 位相同(例如 King–Queen 0.7508、man–woman 0.8323、London–Dublin 0.6913)。

PCA:讀 2024 的詞向量地圖 投影片 85

核心呼叫:prcomp(word_vectors, center = TRUE, scale. = TRUE)。投影片 85 列 King (−2.91, 1.29)、Queen (−2.24, 2.27)、man (−5.64, 2.98),PC1+PC2 保留標準化變異的 38.24%。本機 Python 輸出:

Python 輸出(本機實跑:Python 3.11.2、flair 0.15.1、torch 2.5.1、numpy 1.26.4、gensim 4.4.0)
$ python flair_lab.py --run --output-dir …
…
PCA scores (PC1, PC2, PC3):
King         -2.9121    1.2852   -1.9505
Queen        -2.2414    2.2667   -1.0902
man          -5.6382    2.9845    3.5546
woman        -6.4891    2.4586    3.5669
Paris         3.0702    5.0391   -2.6596
London        5.3196    4.3684   -2.6073
apple         0.3363   -8.6794   -0.4475
orange       -0.0485   -4.4041    0.7715
Taiwan       -2.7994   -4.1493   -6.3330
Dublin        5.8994    1.0633   -0.0927
Bamberg       5.5032   -2.2330    7.2878
PC1 and PC2 retain 38.24% of the standardized variance.
互動:在 PC1–PC2 圖上點一個字,比較「圖上最近」與「全維度 cosine 最近」
PCA Check:投影圖漏掉了什麼?

兩個主成分只保留 38.24% 的變異,剩下 61.76% 不在圖上。圖上靠近不保證全維度相似——上面點 Dublin 試試:圖上它最接近 London 和 Bamberg,但全維度 cosine 上 Bamberg 只有 0.1655。投影片 78、85

E06 作答區 投影片 84

E06:解釋兩個矩陣大小,以及為什麼 security 向量完全相同;若有跑程式,寫下路線和版本

本章小測驗

1. word_vectors 的 11 × 100,列和欄各是什麼?
投影片 83
2. 三個 security 向量兩兩 cosine = 1,原因是?
投影片 84
3. 「PC1+PC2 保留 38.24%」代表?
投影片 85
09 · Lab B:conText

Lab B(17:55–18:10):conText Quick Start C00–C05

以下全部是本機執行 W9/classroom/W9-conText.R 的真實輸出(conText 3.0.1、quanteda 4.5.1、text2vec 0.6.6;執行約 2 秒、R gc 最大使用約 265 MB)。每個數字都和投影片 86–91 對過。

C00:文字、向量、配對的轉換矩陣 投影片 86

R · C00(W9/classroom/W9-conText.R)
# ==== C00: Prepare the three guide objects ====
library(conText)
library(quanteda)
quanteda_options(threads = 1)
data(list = c("cr_sample_corpus", "cr_glove_subset",
  "cr_transform"))
docvars(cr_sample_corpus, "party") <- factor(
  docvars(cr_sample_corpus, "party"), levels = c("D", "R"))
docvars(cr_sample_corpus, "gender") <- factor(
  docvars(cr_sample_corpus, "gender"), levels = c("F", "M"))
toks <- tokens(cr_sample_corpus, remove_punct = TRUE,
  remove_symbols = TRUE, remove_numbers = TRUE,
  remove_separators = TRUE, padding = TRUE)
toks <- tokens_tolower(toks)
toks_nostop <- tokens_select(toks, pattern = stopwords("en"),
  selection = "remove", min_nchar = 3, padding = TRUE)
feats <- featnames(dfm_trim(dfm(toks_nostop),
  min_termfreq = 5))
toks_nostop_feats <- tokens_select(toks_nostop, feats,
  padding = TRUE)
print(c(documents = ndoc(cr_sample_corpus)))
print(rbind(E = dim(cr_glove_subset), A = dim(cr_transform)))
# Empty pads retain the positions of removed tokens.
R console output(本機實跑:conText 3.0.1、quanteda 4.5.1、text2vec 0.6.6)
> library(conText)

> library(quanteda)

> quanteda_options(threads = 1)

> data(list = c("cr_sample_corpus", "cr_glove_subset",
+   "cr_transform"))

> docvars(cr_sample_corpus, "party") <- factor(
+   docvars(cr_sample_corpus, "party"), levels = c("D", "R"))

> docvars(cr_sample_corpus, "gender") <- factor(
+   docvars(cr_sample_corpus, "gender"), levels = c("F", "M"))

> toks <- tokens(cr_sample_corpus, remove_punct = TRUE,
+   remove_symbols = TRUE, remove_numbers = TRUE,
+   remove_separators = TRUE, padding = TRUE)

> toks <- tokens_tolower(toks)

> toks_nostop <- tokens_select(toks, pattern = stopwords("en"),
+   selection = "remove", min_nchar = 3, padding = TRUE)

> feats <- featnames(dfm_trim(dfm(toks_nostop),
+   min_termfreq = 5))

> toks_nostop_feats <- tokens_select(toks_nostop, feats,
+   padding = TRUE)

> print(c(documents = ndoc(cr_sample_corpus)))
documents 
      400 

> print(rbind(E = dim(cr_glove_subset), A = dim(cr_transform)))
  [,1] [,2]
E  500  300
A  300  300

投影片 86 的 Check:哪個物件有文字?cr_sample_corpus(400 篇演說+metadata)。哪兩個必須配對?cr_glove_subset(500 字 × 300 座標)和 cr_transform(300 × 300)。padding = TRUE 讓被刪掉的字留下空位,視窗計算才不會把原本不相鄰的字拉在一起。

C01:一次出現一列 投影片 87

R · C01(W9/classroom/W9-conText.R)
# ==== C01: Keep each immigration context and its metadata ====
immig_toks <- tokens_context(toks_nostop_feats,
  pattern = "immigration", window = 6L, valuetype = "fixed",
  rm_keyword = TRUE)
print(c(contexts = ndoc(immig_toks)))
print(table(docvars(immig_toks, "party")))
print(head(docvars(immig_toks), 3))
# One row is one use of immigration, not one speech.
R console output(本機實跑:conText 3.0.1、quanteda 4.5.1、text2vec 0.6.6)
> immig_toks <- tokens_context(toks_nostop_feats,
+   pattern = "immigration", window = 6L, valuetype = "fixed",
+   rm_keyword = TRUE)
924 instances of "immigration" found.

> print(c(contexts = ndoc(immig_toks)))
contexts 
     924 

> print(table(docvars(immig_toks, "party")))

  D   R 
486 438 

> print(head(docvars(immig_toks), 3))
      pattern party gender nominate_dim1
1 immigration     D      F        -0.402
2 immigration     D      F        -0.402
3 immigration     D      F        -0.402

924 個 contexts,D 486、R 438(投影片 87 ✓)。一列是一次 immigration 的使用,帶著那篇演說的 metadata——不是一篇演說。

C02:語境 → ALC 向量 → 政黨平均 投影片 88

R · C02(W9/classroom/W9-conText.R)
# ==== C02: Build ALC vectors and average within party ====
immig_dfm <- dfm(immig_toks)
immig_dem <- dem(immig_dfm, pre_trained = cr_glove_subset,
  transform = TRUE, transform_matrix = cr_transform,
  verbose = FALSE)
immig_wv_party <- dem_group(immig_dem,
  groups = immig_dem@docvars$party)
print(rbind(DFM = dim(immig_dfm), DEM = dim(immig_dem),
  party_vectors = dim(immig_wv_party)))
# DEM: one context per row. Party vectors: one party per row.
R console output(本機實跑:conText 3.0.1、quanteda 4.5.1、text2vec 0.6.6)
> immig_dfm <- dfm(immig_toks)

> immig_dem <- dem(immig_dfm, pre_trained = cr_glove_subset,
+   transform = TRUE, transform_matrix = cr_transform,
+   verbose = FALSE)

> immig_wv_party <- dem_group(immig_dem,
+   groups = immig_dem@docvars$party)

> print(rbind(DFM = dim(immig_dfm), DEM = dim(immig_dem),
+   party_vectors = dim(immig_wv_party)))
              [,1] [,2]
DFM            924 2014
DEM            924  300
party_vectors    2  300

DEM 924 × 300:每列一個 ALC context 向量;政黨平均 2 × 300(投影片 88 ✓)。Check 的答案:還是 300 個座標,但一列現在代表一個政黨的平均用法。

C03:讀鄰近字 投影片 89

R · C03(W9/classroom/W9-conText.R)
# ==== C03: Read neighbours and compare reform with enforce ====
immig_nns <- nns(immig_wv_party,
  pre_trained = cr_glove_subset, N = 3,
  candidates = immig_wv_party@features, as_list = FALSE)
immig_cosines <- cos_sim(immig_wv_party,
  pre_trained = cr_glove_subset,
  features = c("reform", "enforce"), as_list = FALSE)
print(immig_nns)
print(immig_cosines)
# These party averages are exploratory, before regression adjustment.
R console output(本機實跑:conText 3.0.1、quanteda 4.5.1、text2vec 0.6.6)
> immig_nns <- nns(immig_wv_party,
+   pre_trained = cr_glove_subset, N = 3,
+   candidates = immig_wv_party@features, as_list = FALSE)

> immig_cosines <- cos_sim(immig_wv_party,
+   pre_trained = cr_glove_subset,
+   features = c("reform", "enforce"), as_list = FALSE)

> print(immig_nns)
# A tibble: 6 × 4
  target feature        rank value
  <fct>  <chr>         <int> <dbl>
1 R      immigration       1 0.875
2 D      immigration       1 0.848
3 R      illegal           2 0.708
4 D      broken            2 0.680
5 D      comprehensive     3 0.661
6 R      enforcement       3 0.645

> print(immig_cosines)
  target feature     value
1      D  reform 0.6580804
2      R  reform 0.4899631
3      D enforce 0.4939719
4      R enforce 0.6365299
投影片 89本機
D 鄰居immigration (0.848), broken (0.680), comprehensive (0.661)同 ✓
R 鄰居immigration (0.875), illegal (0.708), enforcement (0.645)同 ✓

投影片沒列的 cos_sim:reform 對 D 0.658、對 R 0.490;enforce 對 D 0.494、對 R 0.637——方向和鄰居一致。這些仍是未調整的描述性平均。

C04:讀鄰近語境 投影片 90

R · C04(W9/classroom/W9-conText.R)
# ==== C04: Read the nearest context to each party vector ====
immig_ncs <- ncs(immig_wv_party, contexts_dem = immig_dem,
  contexts = immig_toks, N = 1, as_list = FALSE)
print(immig_ncs[, c("target", "rank", "value")])
cat(paste(immig_ncs$target, immig_ncs$context, sep = ": "),
  sep = "\n")
# D/R label the queried party vector, not the source speaker.
# These are processed context words, not complete original speeches.
R console output(本機實跑:conText 3.0.1、quanteda 4.5.1、text2vec 0.6.6)
> immig_ncs <- ncs(immig_wv_party, contexts_dem = immig_dem,
+   contexts = immig_toks, N = 1, as_list = FALSE)

> print(immig_ncs[, c("target", "rank", "value")])
# A tibble: 2 × 3
  target  rank value
  <chr>  <int> <dbl>
1 D          1 0.802
2 R          1 0.798

> cat(paste(immig_ncs$target, immig_ncs$context, sep = ": "),
+   sep = "\n")
D: end conversation passed immigration bill comprehensive bill clean broken immigration system year
R: america suggest immigration can good thing illegal immigration legal immigration mean means

D 0.802、R 0.798,兩段文字與投影片 90 相同 ✓。注意:D/R 是被查詢的政黨平均向量,不是說話者的政黨;候選池兩黨都有,而且是處理過的語境字,不是完整原文。

互動:924 個 immigration 語境瀏覽器(真實資料)

每一列是一次使用;分數 = 這個 ALC 向量和 D 平均、R 平均的 cosine(本機 C02 匯出)

提示:排「偏 R」再篩說話者=D,可以找到「民主黨議員用了接近共和黨平均的語境」——這就是為什麼一段被挑出的段落不能代表一黨。

C05:embedding regression,固定 gender 比較政黨 投影片 91

R · C05(W9/classroom/W9-conText.R)
# ==== C05: Compare party while adjusting for gender ====
set.seed(2021L)
fit <- conText(immigration ~ party + gender,
  data = toks_nostop_feats, pre_trained = cr_glove_subset,
  transform = TRUE, transform_matrix = cr_transform,
  jackknife = FALSE, permute = TRUE,
  num_permutations = 100, window = 6L,
  valuetype = "fixed", verbose = FALSE)
print(dim(fit))
print(rownames(fit))
print(fit@normed_coefficients)
# Input is the original processed tokens with metadata, not the DEM.
# Current conText reports squared norms and a bias correction.
# A displayed p.value of 0 means 0 exceedances in 100 permutations.
# These numbers are not the 2023 article's L2 coefficient lengths.
R console output(本機實跑:conText 3.0.1、quanteda 4.5.1、text2vec 0.6.6)
> set.seed(2021L)

> fit <- conText(immigration ~ party + gender,
+   data = toks_nostop_feats, pre_trained = cr_glove_subset,
+   transform = TRUE, transform_matrix = cr_transform,
+   jackknife = FALSE, permute = TRUE,
+   num_permutations = 100, window = 6L,
+   valuetype = "fixed", verbose = FALSE)

> print(dim(fit))
[1]   3 300

> print(rownames(fit))
[1] "(Intercept)" "party_R"     "gender_M"   

> print(fit@normed_coefficients)
  coefficient normed.estimate.orig normed.estimate.deflated normed.estimate.beta.error.null   n
1     party_R            10.139940                 8.668252                        1.471687 924
2    gender_M             6.908761                 5.154713                        1.754048 924
  n_obs covariate_mean p.value
1   924      0.4740260       0
2   924      0.6709957       0
係數投影片 91:去偏平方長度本機 deflated本機 orig(未去偏)置換 p
party_R8.6688.66810.1400
gender_M5.1555.1556.9090
讀這張表的三個注意

① party_R 是固定 gender 下共和黨 vs 民主黨的差異向量;和 C02 的未調整平均不同。② p 顯示 0 的意思是「100 次置換中 0 次超過」,不是 p 真的等於 0(≤ 1/100 的量級)。③ 現行 conText 報告去偏後的平方長度,不是 2023 論文的 L2 長度(.175/.087),兩者不能直接比。投影片 63、91

E04:把一次觀察、證據和係數接起來 投影片 79、91

段落組裝器:每一格選一句,組成一段 E04 答案
E04 答案草稿

本章小測驗

1. C01 的 924 指的是?
投影片 87
2. C05 的 conText() 吃的 data 是?
腳本註解:“Input is the original processed tokens with metadata, not the DEM.” 投影片 91
3. C04 輸出中的 “D:” 代表?
“D/R label the queried party vector, not the source speaker.” 投影片 90
10 · 課堂 R:W9.R

課堂 R:W9.R 的 security 鄰居、原始語境與 PCA 陷阱

W9/classroom/W9.R 是另一條路線:英國下議院 719 篇黨魁演說(W8 同一份樣本)+老師用這份樣本訓練的 30 維教學 GloVe(1,653 字型)。依 Data/README.md,這個模型只訓練五輪,鄰居「明顯有雜訊」,不是驗證過的語意量測。課堂只做 R00、R05;其他是課後。

R00:套件與檔案

R · R00(W9/classroom/W9.R)
# ==== R00 Packages and files ====
required <- c("quanteda", "quanteda.textstats")
missing <- required[!vapply(required, requireNamespace, logical(1), quietly = TRUE)]
if (length(missing)) stop("Install before class: ", paste(missing, collapse = ", "))
suppressPackageStartupMessages({library(quanteda); library(quanteda.textstats)})
quanteda_options(threads = 1)
options(width = 100)
w9_root <- if (dir.exists("W9/classroom")) normalizePath("W9") else if (dir.exists("classroom/Data")) normalizePath(".") else stop("Run from the course repository root or W9.")
speeches <- readRDS(file.path(w9_root, "classroom/Data/w9_speeches.rds"))
speech_corpus <- corpus(speeches, text_field = "text", docid_field = "doc_id")
raw_tokens <- tokens(speech_corpus) # Preserve original contexts for R05 without running R02.
stopifnot(!anyDuplicated(speeches$doc_id), !anyNA(speeches$text), all(nzchar(speeches$text)))
print(c(speeches = ndoc(speech_corpus)))
print(table(speeches$party_family))
print(speeches[1:3, c("doc_id", "leader", "party_family", "date")], row.names = FALSE)
# One row is one complete speech. This is a nearly balanced teaching sample, not all speech volume.
R console output(本機實跑:R 4.5.3(aarch64-conda-linux-gnu)、quanteda 4.5.1、quanteda.textstats 0.97.2)
> required <- c("quanteda", "quanteda.textstats")

> missing <- required[!vapply(required, requireNamespace, logical(1), quietly = TRUE)]

> if (length(missing)) stop("Install before class: ", paste(missing, collapse = ", "))

> suppressPackageStartupMessages({library(quanteda); library(quanteda.textstats)})

> quanteda_options(threads = 1)

> options(width = 100)

> w9_root <- if (dir.exists("W9/classroom")) normalizePath("W9") else if (dir.exists("classroom/Data")) normalizePath(".") else stop("Run from the course repository root or W9.")

> speeches <- readRDS(file.path(w9_root, "classroom/Data/w9_speeches.rds"))

> speech_corpus <- corpus(speeches, text_field = "text", docid_field = "doc_id")

> raw_tokens <- tokens(speech_corpus) # Preserve original contexts for R05 without running R02.

> stopifnot(!anyDuplicated(speeches$doc_id), !anyNA(speeches$text), all(nzchar(speeches$text)))

> print(c(speeches = ndoc(speech_corpus)))
speeches 
     719 

> print(table(speeches$party_family))

Conservative       Labour 
         359          360 

> print(speeches[1:3, c("doc_id", "leader", "party_family", "date")], row.names = FALSE)
        doc_id            leader party_family       date
 ess_hoc_00002 Margaret Thatcher Conservative 1979-05-15
 ess_hoc_00211   James Callaghan       Labour 1979-06-21
 ess_hoc_00004 Margaret Thatcher Conservative 1979-06-26

R05:靜態詞向量與原始語境

R · R05(W9/classroom/W9.R)
# ==== R05 Static word vectors and original contexts ====
# Step 1: Load the word vectors
embedding <- readRDS(file.path(w9_root, "classroom/Data/w9_glove.rds"))
word_vectors <- embedding$vectors
print(dim(word_vectors))

# Step 2: Find security neighbours
word_unit <- word_vectors / sqrt(rowSums(word_vectors ^ 2))
security_cosine <- drop(word_unit %*% word_unit["security", ])
security_cosine["security"] <- NA_real_
top <- head(sort(security_cosine, decreasing = TRUE), 8)
security_neighbours <- data.frame(word = names(top), cosine = unname(top))
print(security_neighbours, row.names = FALSE)

# Step 3: Read the original contexts
security_contexts <- kwic(raw_tokens, pattern = "security",
  valuetype = "fixed", window = 7)
print(head(as.data.frame(security_contexts), 3), row.names = FALSE)
# Every occurrence of security receives the SAME learned vector.
# E04: Name a neighbour, quote a supporting KWIC phrase, then name another security use.
# After E04, continue with the Flair mini-lab. A separate query and PCA are after class.
R console output(本機實跑:R 4.5.3(aarch64-conda-linux-gnu)、quanteda 4.5.1、quanteda.textstats 0.97.2)
> embedding <- readRDS(file.path(w9_root, "classroom/Data/w9_glove.rds"))

> word_vectors <- embedding$vectors

> print(dim(word_vectors))
[1] 1653   30

> word_unit <- word_vectors / sqrt(rowSums(word_vectors ^ 2))

> security_cosine <- drop(word_unit %*% word_unit["security", ])

> security_cosine["security"] <- NA_real_

> top <- head(sort(security_cosine, decreasing = TRUE), 8)

> security_neighbours <- data.frame(word = names(top), cosine = unname(top))

> print(security_neighbours, row.names = FALSE)
        word    cosine
  resolution 0.6612895
     council 0.6608147
    national 0.5949308
      system 0.5732534
   ministers 0.5551598
 conclusions 0.5483960
   discussed 0.5130478
    together 0.5054836

> security_contexts <- kwic(raw_tokens, pattern = "security",
+   valuetype = "fixed", window = 7)

> print(head(as.data.frame(security_contexts), 3), row.names = FALSE)
       docname from   to                                       pre  keyword
 ess_hoc_00308 1876 1876 than unemployed people in terms of social security
 ess_hoc_00308 1916 1916              . When we look at the social security
 ess_hoc_00085  585  585    by the President of the United Nations Security
                                     post  pattern
      benefits . [ Interruption . ] Maybe security
    benefits paid to a striker's family , security
 Council in support of the United Nations security

每一次 security 都拿到同一個學到的向量。鄰居 resolution、council、national… 暗示在這份黨魁演說樣本裡 security 常和聯合國決議、安理會一起出現(這是有雜訊的教學模型,要讀 KWIC 才能確認);KWIC 前三筆就有 social security 和 United Nations Security Council 兩種用法。

PCA 地圖會改變最近的字 投影片 103

投影片 103:在 2D 地圖上離 security 最近的是 discussed;但在全部 30 維,cosine 最高的是 resolution(0.661);PC1+PC2 只保留這個模型單位向量 9.54% 的變異。本機重算(export_W9a.R,對單位向量做 prcomp(center = TRUE)):

R console output(本機實跑)
PCA on unit vectors: PC1+PC2 share = 9.54 %
top full-space neighbour of security: resolution 0.661 
closest on 2D map: discussed 0.014

三個數字都和投影片 103 相同 ✓。

互動:1,653 個字的 PCA 地圖 vs 全維度 cosine(真實 30 維向量)
全 30 維 cosine 最近
2D 地圖上最近(歐氏距離)

security 的原始語境(真實 KWIC,抽 60 筆 / 共 144 筆)

E04(W9.R 版):挑一個鄰居字,找一段支持它的 KWIC,再找一種不同的 security 用法

R06:平均已知字向量並報告覆蓋率(課後)

R · R06(W9/classroom/W9.R)
# ==== R06 Average known word vectors and report coverage ====
# After class, optional. Restore R00, R02, R03, R05 first if the R session was restarted.
# Match count columns to supplied vectors; unseen tokens contribute no vector.
# Repeated terms are weighted by their counts. This is a simple bag-of-vectors average.
embedding_counts <- dfm_match(dfm(content_tokens), features = rownames(word_vectors))
known_tokens <- as.numeric(ntoken(embedding_counts))
all_content_tokens <- as.numeric(ntoken(content_tokens))
embedding_coverage <- data.frame(doc_id = docnames(embedding_counts), known_tokens,
  content_tokens = all_content_tokens,
  coverage = ifelse(all_content_tokens > 0, known_tokens / all_content_tokens, NA_real_))
doc_vectors <- as.matrix(embedding_counts %*% word_vectors)
doc_vectors[known_tokens > 0, ] <- doc_vectors[known_tokens > 0, , drop = FALSE] / known_tokens[known_tokens > 0]
doc_norms <- sqrt(rowSums(doc_vectors ^ 2))
valid_embedding <- known_tokens > 0 & is.finite(doc_norms) & doc_norms > 0
doc_unit <- doc_vectors[valid_embedding, , drop = FALSE] / doc_norms[valid_embedding]
embedding_similarity <- tcrossprod(doc_unit)
diag(embedding_similarity) <- NA_real_
stopifnot(query_id %in% rownames(embedding_similarity))
embedding_rank <- order(embedding_similarity[query_id, ], decreasing = TRUE, na.last = NA)
embedding_neighbours <- data.frame(doc_id = colnames(embedding_similarity)[head(embedding_rank, 5)],
  cosine = embedding_similarity[query_id, head(embedding_rank, 5)], row.names = NULL)
embedding_neighbours$coverage <- embedding_coverage$coverage[match(embedding_neighbours$doc_id, embedding_coverage$doc_id)]
print(summary(embedding_coverage$coverage))
print(embedding_neighbours, row.names = FALSE)
cat("Excluded zero embedding documents:", sum(!valid_embedding), "\n")
# Word order and negation scope disappear in this average. These vectors are static,
# not contextual transformer embeddings or a conText/ALC estimate of contextual meaning.
# E05: Compare count, TF-IDF and embedding neighbours for the same query. Support one
# interpretation with original text and report coverage. Why is a high cosine score
# insufficient to claim agreement, influence or a causal effect?
R console output(本機實跑:R 4.5.3(aarch64-conda-linux-gnu)、quanteda 4.5.1、quanteda.textstats 0.97.2)
> embedding_counts <- dfm_match(dfm(content_tokens), features = rownames(word_vectors))

> known_tokens <- as.numeric(ntoken(embedding_counts))

> all_content_tokens <- as.numeric(ntoken(content_tokens))

> embedding_coverage <- data.frame(doc_id = docnames(embedding_counts), known_tokens,
+   content_tokens = all_content_tokens,
+   coverage = ifelse(all_content_tokens > 0, known_tokens / all_content_tokens, NA_real_))

> doc_vectors <- as.matrix(embedding_counts %*% word_vectors)

> doc_vectors[known_tokens > 0, ] <- doc_vectors[known_tokens > 0, , drop = FALSE] / known_tokens[known_tokens > 0]

> doc_norms <- sqrt(rowSums(doc_vectors ^ 2))

> valid_embedding <- known_tokens > 0 & is.finite(doc_norms) & doc_norms > 0

> doc_unit <- doc_vectors[valid_embedding, , drop = FALSE] / doc_norms[valid_embedding]

> embedding_similarity <- tcrossprod(doc_unit)

> diag(embedding_similarity) <- NA_real_

> stopifnot(query_id %in% rownames(embedding_similarity))

> embedding_rank <- order(embedding_similarity[query_id, ], decreasing = TRUE, na.last = NA)

> embedding_neighbours <- data.frame(doc_id = colnames(embedding_similarity)[head(embedding_rank, 5)],
+   cosine = embedding_similarity[query_id, head(embedding_rank, 5)], row.names = NULL)

> embedding_neighbours$coverage <- embedding_coverage$coverage[match(embedding_neighbours$doc_id, embedding_coverage$doc_id)]

> print(summary(embedding_coverage$coverage))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
 0.5185  0.7533  0.8025  0.7980  0.8491  1.0000 

> print(embedding_neighbours, row.names = FALSE)
        doc_id    cosine  coverage
 ess_hoc_00174 0.9018980 0.8191781
 ess_hoc_00042 0.9004335 0.8346667
 ess_hoc_01328 0.8860238 0.8160677
 ess_hoc_00430 0.8856149 0.7838710
 ess_hoc_02293 0.8826469 0.8145957

> cat("Excluded zero embedding documents:", sum(!valid_embedding), "\n")
Excluded zero embedding documents: 0 

文件向量=已知 token 向量的計數加權平均(投影片 102 的做法)。腳本註解提醒:語序與否定範圍在平均裡消失;這是靜態向量平均,不是 transformer 也不是 conText/ALC。

R01:可讀性(Flesch 與 LIX) 投影片 111–112

R · R01(W9/classroom/W9.R)
# ==== R01 Readability from original text ====
# After class: full code and E01. In class, the teacher briefly previews saved output.
readability <- textstat_readability(speech_corpus, measure = "Flesch",
  remove_hyphens = TRUE, min_sentence_length = 1, max_sentence_length = 10000,
  intermediate = TRUE)
readability$words_per_sentence <- readability$W / readability$St
# Installed quanteda.textstats 0.97.2 has no named LIX measure. W7C is its
# intermediate count of words of at least seven characters (= more than six).
readability$LIX <- readability$words_per_sentence + 100 * readability$W7C / readability$W
# Cross-check the implementation's historical LIW label against the transparent formula.
lix_check <- textstat_readability(speech_corpus, measure = "LIW")
stopifnot(isTRUE(all.equal(readability$LIX, lix_check$LIW)))
readability$party <- speeches$party_family[match(readability$document, speeches$doc_id)]
print(head(readability[, c("document", "Flesch", "LIX", "W", "St", "words_per_sentence")], 4), row.names = FALSE)
readability_summary <- aggregate(cbind(Flesch, LIX, words_per_sentence) ~ party,
  readability, FUN = median)
print(readability_summary, row.names = FALSE)
# Flesch uses sentence length and estimated English syllables. Higher scores indicate
# easier reading under this formula; they do not measure reader comprehension directly.
# LIX = words/sentences + 100*(words with more than six characters)/words.
# Higher LIX indicates harder reading under this formula. LIX connects to the
# Bischof & Senninger (2018) assigned study; Flesch is a teaching comparison.
# E01: Read one high-LIX and one low-LIX speech, then compare their Flesch scores.
# Which language choices do the formulas capture? Name one important aspect of
# comprehension that they cannot observe. State the opposite score directions.
R console output(本機實跑:R 4.5.3(aarch64-conda-linux-gnu)、quanteda 4.5.1、quanteda.textstats 0.97.2)
> readability <- textstat_readability(speech_corpus, measure = "Flesch",
+   remove_hyphens = TRUE, min_sentence_length = 1, max_sentence_length = 10000,
+   intermediate = TRUE)

> readability$words_per_sentence <- readability$W / readability$St

> readability$LIX <- readability$words_per_sentence + 100 * readability$W7C / readability$W

> lix_check <- textstat_readability(speech_corpus, measure = "LIW")

> stopifnot(isTRUE(all.equal(readability$LIX, lix_check$LIW)))

> readability$party <- speeches$party_family[match(readability$document, speeches$doc_id)]

> print(head(readability[, c("document", "Flesch", "LIX", "W", "St", "words_per_sentence")], 4), row.names = FALSE)
      document   Flesch      LIX   W St words_per_sentence
 ess_hoc_00002 67.95802 35.75018 603 42           14.35714
 ess_hoc_00211 69.10086 33.34576 322 21           15.33333
 ess_hoc_00004 38.39723 54.16042 445 18           24.72222
 ess_hoc_00006 44.02528 48.32183 712 28           25.42857

> readability_summary <- aggregate(cbind(Flesch, LIX, words_per_sentence) ~ party,
+   readability, FUN = median)

> print(readability_summary, row.names = FALSE)
        party   Flesch      LIX words_per_sentence
 Conservative 58.21930 42.02824           20.46667
       Labour 57.24104 42.95662           21.75000
方向相反

LIX=每句字數+長字(> 6 字元)百分比,越高越難;Flesch Reading Ease 越高越容易。兩黨中位數:Conservative Flesch 58.22/LIX 42.03,Labour 57.24/42.96。切句子會同時改變兩個分數,政策內容卻沒變。投影片 112

11 · 補充投影片

補充投影片 95–112:manufacturing、評估、情緒量測、可讀性

總統怎麼談 manufacturing? 投影片 104–105

GRS 2022 §8.2.7(p. 85):美國國情咨文,1900–1959 vs 1960–2016,共 53 次 manufacturing。① 收集每次出現周圍的字;② 用預訓練嵌入表示;③ 每個時期內平均並套學到的線性轉換——à la carte,每個時期得到一個 300 維 manufacturing 向量。鄰居:早期 exportation、oil-related(貿易、能源),後期 retooling、jobs、energy-intensive、offshoring(重組、就業)。

替用途驗證表示 投影片 106

評估問題
Intrinsic(內在)向量關係是否符合外部對字的判斷?
Extrinsic(外在)向量能不能幫下游任務,例如預測標籤?
Substantive(實質)這個比較能不能支持研究問題需要的詮釋?

GRS 2022 §8.4, p. 87。投影片的討論題:manufacturing 的時期對比,要讀哪些段落來檢查?

W10 比較:德國政治文本的情緒量測 投影片 107–108

Widmann & Wich (2023):9,898 句標註過的議會演說與政黨 Facebook 貼文;三條路線:鄰居擴充的 ed8 字典、word2vec 句子平均+神經網路、微調 ELECTRA。保留句的 F1:

模型AngerFear
ed8.59.52
word2vec + NN.79.55
ELECTRA.84.64

Table 1, p. 634;作者另用新的隨機句樣本測試,穩健性檢查 pp. 635–638。

依用途評估嵌入 投影片 110

向量的用途要檢查什麼
預測用的特徵保留文本或新語料上的表現
政治語言的量測人類判斷、原始段落、適當基準
跨語料比較領域、詞彙覆蓋、跨模型設定的穩定性
社會聯想目標與屬性字集、來源語料組成、比較的敏感度

Rodriguez & Spirling (2022) 比較視窗大小、維度、多次訓練與人類對字詞聯想的判斷(pp. 105–108, 112–113)。

主張判斷題

「W9.R 的 30 維 GloVe 說 security 最近的是 resolution,所以英國黨魁把安全理解為聯合國決議。」
Data/README.md:“produces visibly noisy neighbours. It is not a validated semantic measure.”
「ELECTRA 的 Anger F1 .84 高於 ed8 的 .59,所以字典方法沒有用。」
投影片 108、110(補充推論)
「LIX 從 40 升到 45,表示這份黨綱變得比較好讀。」
投影片 112
12 · 文獻導讀

文獻導讀:三篇指定閱讀

Rodriguez, Spirling & Stewart (2023). Embedding Regression. APSR 117(4): 1255–1274 投影片 58–71

全文:Cambridge 開放取用版(CC BY 4.0),本機讀過全文;頁碼為期刊頁碼。

項目內容頁碼
研究問題社會科學常想知道字詞用法如何隨時間、黨派或其他文件層級共變數而變,例如兩黨對 “immigration” 的理解有何不同;作者提出 à la carte on text(conText)embedding regression 模型來回答。p. 1255(摘要)
資料主要應用用美國國會紀錄第 111–114 屆(Gentzkow, Shapiro & Taddy 2018);另有 Rodman (2020) NYT 語料的重現、Trump/trump 區分、英美 “Empire”(Hansard 對國會紀錄)與保守黨後座議員的 EU 情感。pp. 1257, 1261–1264, 1269–1271
方法ALC:取目標字周圍語境字的預訓練向量平均,乘上矩陣 A;A 用來降低常見但無資訊的字在平均裡的權重。把每次出現的 ALC 向量當多變量結果,對群體指標回歸;係數取長度(norm),用置換檢定與 bootstrap 評估不確定性。pp. 1258–1260, 1264–1265
發現ALC 在 Rodman 語料上表現與原研究相當,少量文件也可用;區分 Trump/trump 時接近 RoBERTa。immigration 的政黨差異大於性別差異(Figure 5),民主黨鄰居偏改革、共和黨偏執法(Table 4–5)。pp. 1261–1263, 1266–1267
限制與建議無需調參但仍有選擇:視窗大小、前處理;ALC 語境的前處理要和估計嵌入與 A 時一致;資料少時用大型預訓練向量(如 Stanford GloVe)是合理近似,可再估計語料專屬的 A。最終的實質詮釋仍需研究者自行驗證(語意、聚合建構、預測效度等)。pp. 1268–1270
和本週方法的關係就是 Lab B 的 conText();ch06–ch07、ch09。—

Rodriguez & Spirling (2022). Word Embeddings: What Works, What Doesn’t, and How to Tell the Difference for Applied Research. JOP 84(1): 101–115 投影片 110

全文:本機拿不到(JOP 非開放取用)。下表只依投影片 110 與 reading README,頁碼是投影片引用的頁碼。

項目依投影片的內容
主題為研究任務選擇與評估詞嵌入(README)。
做法比較視窗大小、維度、多次訓練,並對照人類對字詞聯想的判斷(pp. 105–108, 112–113)。
和本週的關係投影片 110「依用途評估嵌入」的依據;RSS (2023) 的實驗也延伸它(RSS 2023 p. 1268)。

Bischof & Senninger (2018). Simple Politics for the People? EJPR 57(2): 473–495 投影片 111–112

全文:Unpaywall 指向奧胡斯大學 Pure 的接受稿,但本機下載得到的是網頁而不是 PDF,所以沒有讀到全文。下表只依投影片 111–112。

項目依投影片的內容
研究問題政黨黨綱越簡單,選民對政黨的左右定位是否越接近專家定位?(pp. 477–481, 486–490)
資料與量測德國與奧地利黨綱,用 LIX 量複雜度;比較選民與專家的左右定位。
發現越簡單的黨綱,定位差距越小。
量測提醒LIX 越高越複雜、Flesch 越高越容易;切句子會改變分數但不改政策內容(p. 479)。
和本週的關係W9.R 的 R01(ch10)。
要補全文的話

Rodriguez & Spirling (2022) 可用學校圖書館權限從 doi:10.1086/715162 下載;Bischof & Senninger (2018) 可從 doi:10.1111/1475-6765.12235 或奧胡斯大學 Pure 頁面下載接受稿。取得全文後可再補上附頁碼的完整導讀卡。

13 · 陷阱與詞彙

常見陷阱與詞彙表

十個常見陷阱

1. 以為 Flair 一定是情境化

WordEmbeddings("glove") 是靜態查表;三個 security cosine = 1。投影片 11、84

2. 把 PCA 圖上的距離當相似度

11 字圖只保留 38.24%,W9.R 的 30 維模型只保留 9.54%;2D 最近是 discussed、全維度最近是 resolution。投影片 85、103

3. 把 PC1 直接叫意識形態

Rheault & Cochrane 要用 Voteview 驗證(r = 0.918)才這樣讀。投影片 24

4. cosine 回升=舊用法回來

Rodman 的 social–equality 要回去讀段落。投影片 36

5. 嵌入擴充字典一定更好

Müller & Proksch:擴充後一致性 .61 → .54。投影片 43

6. E 和 A 混搭

cr_glove_subset 和 cr_transform 是配對;換自己的向量要配自己的 A。投影片 59、86

7. 一列=一篇演說

conText 的一列是一次出現(924 contexts,不是 400 篇)。投影片 87

8. 把 C02 平均當成調整後的比較

只有 C05 的 party_R 固定了 gender。投影片 89、91

9. 拿 8.668 跟論文 .175 比

現行 conText 報去偏平方長度,論文是 L2 長度;資料也不同。投影片 63、91

10. 用一段被挑出的段落代表一黨

段落只說明對比;估頻率要更廣的樣本。C04 的 D/R 是被查詢的平均向量,不是說話者。投影片 69、90

詞彙表

14 · 總複習

總複習、研究設計與參考文獻

章末測驗(20 題)

尚未作答

用一段話設計嵌入研究 投影片 92

投影片 92 的三步:① 從政治問題和「什麼拿到向量」開始;② 為這個問題選語料、表示法和比較;③ 找出可能改變詮釋的證據。題目:怎麼比較一個政策詞在政黨、時期或立法場域之間的用法?

計畫填寫器(匯出 Markdown,可接作業)
Markdown

學習進度

參考文獻 投影片 93–94

W9 指定閱讀

  • Bischof, Daniel, and Roman Senninger. 2018. “Simple Politics for the People? Complexity in Campaign Messages and Political Knowledge.” European Journal of Political Research 57(2): 473–495. doi:10.1111/1475-6765.12235
  • Rodriguez, Pedro L., and Arthur Spirling. 2022. “Word Embeddings: What Works, What Doesn’t, and How to Tell the Difference for Applied Research.” The Journal of Politics 84(1): 101–115. doi:10.1086/715162
  • Rodriguez, Pedro L., Arthur Spirling, and Brandon M. Stewart. 2023. “Embedding Regression: Models for Context-Specific Description and Inference.” American Political Science Review 117(4): 1255–1274. doi:10.1017/S0003055422001228

案例與延伸

  • Rheault, Ludovic, and Christopher Cochrane. 2020. “Word Embeddings for the Analysis of Ideological Placement in Parliamentary Corpora.” Political Analysis 28(1): 112–133. doi:10.1017/pan.2019.26
  • Rodman, Emma. 2020. “A Timely Intervention: Tracking the Changing Meanings of Political Concepts with Word Vectors.” Political Analysis 28(1): 87–111. doi:10.1017/pan.2019.23
  • Müller, Stefan, and Sven-Oliver Proksch. 2024. “Nostalgia in European Party Politics: A Text-Based Measurement Approach.” British Journal of Political Science 54(3): 993–1005. doi:10.1017/S0007123423000571(W10 選讀)
  • Wirsching, Elisa M., Pedro L. Rodriguez, Arthur Spirling, and Brandon M. Stewart. 2025. “Multilanguage Word Embeddings for Social Scientists.” Political Analysis 33(2): 156–163. doi:10.1017/pan.2024.17
  • Widmann, Tobias, and Maximilian Wich. 2023. “Creating and Comparing Dictionary, Word Embedding, and Transformer-Based Models to Measure Discrete Emotions in German Political Text.” Political Analysis. doi:10.1017/pan.2022.15(W10 比較)
  • Gonthier (2025) doi:10.1111/spsr.12649;Karell & Sachs (2023) doi:10.1177/23780231231212108;Van Matre et al. (2026) doi:10.1111/psj.70079;Kim & Kesari (2021) doi:10.54501/jots.v1i1.13

教科書、課程材料與軟體

  • Grimmer, J., M. E. Roberts, and B. M. Stewart. 2022. Text as Data. Princeton University Press. 第 8 章(第 7 章:相似度與 TF–IDF)。
  • Schoonvelde, Martijn. 2026. Essex Summer School, Introduction to Quantitative Text Analysis, Day 3, “Comparing representations.”
  • conText(R)Quick Start:github.com/prodriguezsosa/conText;Flair 0.15.1 WordEmbeddings("glove");quanteda、quanteda.textstats。
本教材依據 NTLDEV 7191 W9 投影片(Yen-Chieh Liao 廖彥傑,投影片標示日期 2026-11-06;PDF 112 頁)、W9/README.md、W9/lab/README.md、W9/reading/README.md、W9/classroom/W9.R、W9-conText.R、W9/classroom/Data/README.md、W9/lab/flair/ 製作(upstream commit 3ffaf9f)。R 輸出為本機重新執行(R 4.5.3(aarch64-conda-linux-gnu)、quanteda 4.5.1、quanteda.textstats 0.97.2;conText:conText 3.0.1、quanteda 4.5.1、text2vec 0.6.6);Flair 為 Python 路線本機執行(Python 3.11.2、flair 0.15.1、torch 2.5.1、numpy 1.26.4、gensim 4.4.0)。RSS (2023) 導讀卡依開放取用全文;另兩篇只依投影片。標示「補充(非講義內容)」的段落與玩具示範為額外說明。製作日期 2026-11-13。
NTLDEV 7191 Text as Data · W9 互動自學教材 · 依據 2026-11-06 課程投影片製作(2026-11-13)