W9:詞嵌入與政治語言(Word Embeddings and Political Language)
W8 的主題模型回答「大家在談什麼、談多少」。W9 換一個問題:同一個字在不同人、不同時期嘴裡是不是用法不一樣?做法是把字(或字的每一次出現)變成一串從語料學來的數字——向量(vector),再用 cosine 比較方向。本週有四個政治學案例、一個 Flair 小 Lab、一個 conText(embedding regression)Lab。
開場問題:security 在說什麼?
投影片 2 用 security 起頭:同一個字會出現在國防(Security Council)、能源(energy security)、經濟(social security)三種語境。老師拋出兩個問題:哪些鄰近的字幫我們分辨這些用法?以及怎麼檢驗這些用法在政黨或時期之間有沒有差異?整週就是在回答這兩題。
想像你只能從「一個字旁邊常出現哪些字」來猜它的意思。security 旁邊出現 council、nations,大概是聯合國;出現 social、benefits,大概是社福。詞嵌入就是把這種「旁邊都是誰」的資訊壓成一串數字。本週後半的 embedding regression 再更進一步:每一次出現都給一個向量,才能比較民主黨和共和黨怎麼用同一個字。
本週要能說明的事
整理自投影片 77 的 Lab 目標(「向量代表什麼、怎麼比較、怎麼檢查詮釋」)與投影片 92 的研究設計三步驟。讀完一章後回來勾選:
- 向量代表什麼:分清楚「一個字型(word type)一個向量」(靜態 GloVe)與「一次出現(occurrence)一個向量」(ALC/conText)。
- 怎麼比較:會算、會讀 cosine;知道 PCA 2D 圖上的距離不等於全維度的 cosine。
- 四個案例:每個研究「什麼拿到向量、比較什麼、用什麼證據支撐政治詮釋」。
- conText 結果:解釋
party_R在「固定 gender」下比較什麼,並用一個鄰居字和一段 context 支撐。 - 設計自己的研究:寫一段話說明問題、單位、語料、表示法、比較方式與會改變結論的證據。
課堂路線(110 分鐘)
依 W9/README.md:全套 112 張,主講 1–94,補充 95–112;Lab 30 分鐘(17:40–18:10)。點每一段看重點:
| 段落 | 投影片 | 問題(README 原文意譯) |
|---|---|---|
| 概念與研究地圖 | 1–16 | 向量代表什麼?怎麼學出來? |
| Case 1 · Rheault & Cochrane | 17–26 | 議會語言能不能定位政黨? |
| Case 2 · Rodman | 27–36 | 字詞關聯能不能揭露概念變遷? |
| Case 3 · Müller & Proksch | 37–46 | 鄰居字怎麼幫忙建立並驗證懷舊量測? |
| Case 4 · Embedding regression | 47–71 | 怎麼比較不同群體對同一個字的用法? |
| 多語資源與應用 | 72–76 | 這個方法還用在哪裡? |
| Lab 導覽與休息 | 77–80 | Lab 要比較什麼? |
| Flair 與 PCA | 81–85 | 載入 GloVe、取得向量、比較 security、讀投影圖 |
| conText | 86–91 | 建 context 向量、讀鄰居與段落、固定 gender 比較政黨 |
| 研究設計與參考文獻 | 92–94 | 什麼證據能支持我們自己的比較? |
| 補充 | 95–112 | 額外概念、情緒量測、評估、可讀性 |
四個案例一覽
| 案例 | 文本 | 什麼拿到向量 | 怎麼回答問題 |
|---|---|---|---|
| 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)。
怎麼使用本教材
- 右側「投影片對照」會跟著段落切到對應頁;每個 標籤都可以點。
- 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)。每個數字都對過投影片,對不上的地方會兩邊並列。
- 標「補充(非講義內容)」的是我加的白話說明或玩具示範,不是老師的投影片內容。
本章小測驗
從 one-hot 到詞嵌入:視窗、CBOW/Skip-gram、cosine
one-hot 的問題:每個不同的字 cosine 都是 0
投影片 3–6(依 Hung-yi Lee 教學圖與 Grimmer, Roberts & Stewart 2022 第 8 章 p. 78):one-hot 給每個字一個專屬座標,所以 dog 和 cat 的向量完全不重疊,cosine = 0,看不出它們很像。詞嵌入改成「從用法學來的座標」,dog、cat、rabbit 出現在相似語境時就會靠近。
嵌入座標是我自己編的 3 維玩具值,只為了示範「one-hot 全是 0、嵌入有遠近」;真實模型是 30、100 或 300 維。
上下文視窗:c = 1 與 c = 2
投影片 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(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
| security | forces | energy | |
|---|---|---|---|
| Defence (a) | |||
| Energy (b) |
cosine 只看方向、不看長度。把 Defence 演說每個計數都乘 10(變成很長的演說),cosine 仍是 0.50——試試看把上面 a 列改成 10, 10, 0。
用預測學座標
補充投影片 95–98:輸入是一個詞彙位置(one-hot),中間是學到的座標 z1、z2,輸出是下一個字的機率(目標 attends);預測錯誤會更新連線權重。學完後留下的中間層權重就是詞向量。投影片 99(GRS 2022 §8.1, p. 80)的影評例子說明為什麼這有用:訓練資料裡有 great,新影評用 fantastic;如果兩個字向量相近,分類器能把學到的東西「帶過去」。
本章小測驗
訓練選擇決定你拿到哪種向量
四種方法、兩種表示
| 方法或介面 | 學習訊號 | 表示 |
|---|---|---|
| Word2Vec | CBOW: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") 是查表:同一個字型永遠回傳同一列。
每一列代表什麼?
投影片 100(Schoonvelde 2026, ESS Day 3, p. 6):文件計數矩陣每一列是一篇演說的特徵計數;靜態詞嵌入每一列是一個字型學到的座標。比較兩篇演說 → 比 DFM 的兩列;比較兩個字 → 比嵌入矩陣的兩列。
把字向量平均成文件向量
投影片 102(GRS 2022 §8.3, pp. 86–87):逐座標平均。第一個 token (1, 0)、第二個 (0, 2),文件平均 (0.5, 1.0)。重複出現的字會重複貢獻。W9.R 的 R06 就是這樣做文件向量(ch10)。
翻牌卡:靜態還是情境化?
本章小測驗
Case 1 · Rheault & Cochrane (2020):從議會發言定位政黨
問題與資料
背景:記名表決(roll-call votes)是定位政黨的一種方法。問題:發言能不能也揭露政黨位置,以及位置在各屆之間怎麼變?文本:美國、英國、加拿大的議會辯論;模型為每個政黨在每一屆學一個向量。(Political Analysis 28(1): 112–133)
怎麼用嵌入:Predict → Represent → Project
- Predict:模型從上下文加上 party-term 標籤預測字(例子是 work)。
- Represent:每個 party-term 得到一個向量,例如 Labour 2005。
- Project:用 PCA 把所有 party-term 向量投影,在 PC1 上比較。
來源:投影片 18 引作者 preprint Figure 1, p. 8。
讀圖:PC1 隨年份
橫軸是年份、縱軸是 PC1(party-term 向量變異最大的方向)。1920 年附近兩黨差距小(民主黨藍色虛線、共和黨紅色實線);到 2000 年兩黨在這個發言量尺上遠得多。(作者 preprint Figure 2b, p. 15)
在模型之外驗證
| 美國眾議院(1921–2016) | 數字 |
|---|---|
| 發言 PC1 與 Voteview 政黨平均的相關 | 0.918 |
| party-term 配對排序一致率 | 85.66% |
結論:在這段重疊期間可以把 PC1 讀成左右量尺;但一致程度隨基準而不同。(作者 preprint Table 2, p. 20)
PCA 只保證 PC1 是「變異最大的方向」,不保證它是意識形態——也可能是年代、議題或議事程序。拿獨立的 Voteview 來比,才有理由叫它 left–right。這和 W7 Wordfish 的道理一樣。
本章小測驗
Case 2 · Rodman (2020):equality 的意思怎麼變
問題與資料
背景:equality 這個字一直存在,但圍繞它的辯論一直在變。問題:不同年代,哪些群體與議題和 equality 連在一起?文本:NYT Article API 中標題含 equality 的 3,105 則新聞,1855–2016。(Political Analysis 28(1): 87–111)
新聞語境變成歷史證據
| 研究步驟 | Rodman 怎麼做 |
|---|---|
| 收集語境 | 用標題、摘要和(若有)第一段;把新聞分成七個年代。 |
| 估計嵌入 | 比較四種 Word2Vec 訓練方案,每種都產生各年代的詞向量。 |
| 追蹤關聯 | 在每個年代內算 equality 與選定字的 cosine,再跨年代追蹤。 |
投影片 28 引作者手稿 §§5.2, 5.4。
選模型:哪個最接近人工編碼?
讀欄位:偏差(deviation)越低、與基準的相關越高越好。chronological 那一列相關最高(0.611)、偏差最低,最接近五個人工編碼的主題趨勢。Rodman 接著用它追蹤新的字對。(作者手稿 Table 2, p. 25)
四種訓練方案都「能跑」,但只有拿人工編碼當基準,才知道哪個最可信。這是 ch11 會講的 substantive/extrinsic 評估:不是看向量漂不漂亮,而是看它能不能重現人類判斷。
讀 social–equality 曲線
「回升到 .30,是否表示早期用法還在?」投影片 36 的答案是:要回去讀段落。同樣的 cosine 可以來自完全不同的用法。
本章小測驗
Case 3 · Müller & Proksch (2024):用鄰居字建懷舊字典
問題與資料
背景:提到過去可以是讚美、批評或懷舊。問題:文化保守的政黨是不是更常訴諸「更好的過去」?文本:24 個歐洲國家、1,648 份黨綱,1946–2018。(BJPS 54(3): 993–1005;本篇是 W10 選讀,W9 拿來當案例。)
從鄰居字到懷舊量測
- 找候選字:在預訓練 GloVe 和用黨綱訓練的向量中,搜尋種子字的鄰居。
- 篩選:三位編碼者審查鄰居字;通過的字組成 embeddings-based 字典。
- 計分:結合兩本字典;每 1,000 句被標記的句數成為比較政黨的結果變數。
投影片 38 引 Figure 1 panels 1–2, p. 996;Supplement §B.2。
下面是「如果種子字是 tradition」時嵌入可能給的鄰居類型(我編的示範字,不是論文的字表)。勾選你會留進懷舊字典的字,再看提示。
先驗證量測,再比較政黨
他們比較字典(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)
跨六種量測比較政黨
六個標準化懷舊分數當欄位;M2 用擴充字典、M4 另外要求正面情感。框起來的那一列:M2 是 .08、M4 是 .07。文化保守量尺每高一分,黨綱懷舊高 .07–.10 個標準差(六個模型、控制其他變數)。(Table 1, p. 1001;文化保守量尺見 Supplement §C.6)
本章小測驗
Case 4 直覺:同一個字、不同語境 → ALC → 回歸
chips:英國薯條、美國洋芋片
同一個字 chips:英國用法旁邊有 ketchup、knife and fork(熱薯條);美國用法旁邊有 a bag(洋芋片)。這裡的「意思」就是使用模式。(投影片註明是構造的例子;Embedding Regression Non-Technical Explainer §1)
一個語境變成一個 ALC 向量
- 查表:在同一個預訓練空間裡查語境字的向量。
- 平均:ui = (1/|Ci|) Σw∈Ci vw(這一次出現周圍的字)。
- 校準:yi = A ui;A 是學到的線性轉換,修正「平均」造成的偏差。
一次使用 → 一個向量。同一個字的不同用法,可以在同一空間裡拿到不同表示。
直接平均語境字向量時,常見字(像 the、and)會把所有平均都拉向同一個方向。Khodak et al. (2018) 的 à la carte 方法學一個矩陣 A,讓「語境平均經 A 轉換後」盡量接近該字原本的預訓練向量。conText 的 cr_transform 就是配合 cr_glove_subset 學好的 A——所以投影片一直強調 E 和 A 必須是 matched pair。
ALC 玩具計算機(補充(非講義內容))
2 維玩具空間(數字是我編的):x 軸≈「熱食/餐具」,y 軸≈「包裝零食」。勾選這一次 chips 出現時旁邊的字:
context 向量就是回歸的結果變數
觀察值 = 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:從語境到回歸
| 步驟 | 內容 |
|---|---|
| 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:一組配對。
本章小測驗
Case 4 結果:immigration、多語擴充與其他應用
問題與資料
背景:兩黨提到 immigration 的次數可能一樣多,但用的語境不同。問題:同一個字的用法怎麼隨政黨和性別而變?文本:美國國會紀錄(Congressional Record)第 111–114 屆。(APSR 117(4): 1255–1274,W9 核心閱讀)
比較政黨與性別差異的長度
高度=調整後差異向量的長度:0 表示沒有向量差異,越大差異越大;誤差線是 95% bootstrap 區間。immigration:政黨 .175(固定性別)、性別 .087(固定政黨)。三個政治詞的政黨差距都比較大。(Figure 5;Supplement Table J.4)
左:論文 Figure 5/Table J.4 的 L2 長度(投影片 63)。右:本機重跑 Quick Start 的 normed.estimate.deflated(去偏後的平方長度,投影片 91)。兩組單位不同、資料規模也不同(Lab 只有 400 篇樣本),只能各自比較「政黨 > 性別」這個方向。
群體差異裡有什麼?鄰居字
每一列是和該黨估計的 immigration 向量 cosine 最近的十個字。框起來的部分:民主黨附近是改變制度(changing the system),共和黨附近是執行現行法律(enforcing existing law);enact、legislation 兩列都有。(Table 4, p. 1267)
回到原始段落
讀和各黨估計向量最近的段落:民主黨的段落談 reform、共和黨的段落談 enforcement。範圍限制:這些段落只是說明對比;要估計某種用法多常見,需要更廣的樣本。(Table 5, p. 1267)
英文以外:多語嵌入
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 應用
| 研究 | 比較 |
|---|---|
| Gonthier (2025) · SPSR | 不同意識形態群體怎麼用法文 peuple |
| Van Matre et al. (2026) · PSJ | 氣候框架 × 政黨 × 國會屆次 |
| Karell & Sachs (2023) · Socius | 政治訊號(Trump 回歸 Twitter)前後的少數群體語言 |
| Kim & Kesari (2021) · JOTS | “Chinese virus”:仇恨/反仇恨 × 時間 |
本章小測驗
Lab A(17:40–17:55):Flair 載入靜態 GloVe、比較 security、讀 PCA
F00:課前準備環境與模型
投影片 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
課堂用的是 R 版 flair_steps.R(三段和 Python 版一一對應):
# 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 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_length | 100(投影片 82) | 100 ✓ |
| 11 個字的矩陣 | 11 × 100(投影片 83) | (11, 100) ✓ |
| 三句 security | 3 × 100,兩兩 cosine 1(投影片 84) | (3, 100)、全為 1 ✓ |
Social security、Security Council、Energy security 三種完全不同的用法,靜態查表回傳同一個字型向量,所以 cosine = 1。這正是 Case 4 要解決的問題:靜態向量把一個字所有用法混在一起。(注意 GloVe 先轉小寫,Security 和 security 查到同一列。)
11 × 11 全維度 cosine(本機 flair_lab.py --run 實跑)
數字和老師 repo 的 W9/lab/flair/example-output/word-cosine.csv 到小數第 4 位相同(例如 King–Queen 0.7508、man–woman 0.8323、London–Dublin 0.6913)。
PCA:讀 2024 的詞向量地圖
核心呼叫: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 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.
兩個主成分只保留 38.24% 的變異,剩下 61.76% 不在圖上。圖上靠近不保證全維度相似——上面點 Dublin 試試:圖上它最接近 London 和 Bamberg,但全維度 cosine 上 Bamberg 只有 0.1655。
E06 作答區
本章小測驗
word_vectors 的 11 × 100,列和欄各是什麼?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:文字、向量、配對的轉換矩陣
# ==== 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.> 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:一次出現一列
# ==== 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.
> 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.402924 個 contexts,D 486、R 438(投影片 87 ✓)。一列是一次 immigration 的使用,帶著那篇演說的 metadata——不是一篇演說。
C02:語境 → ALC 向量 → 政黨平均
# ==== 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.
> 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 300DEM 924 × 300:每列一個 ALC context 向量;政黨平均 2 × 300(投影片 88 ✓)。Check 的答案:還是 300 個座標,但一列現在代表一個政黨的平均用法。
C03:讀鄰近字
# ==== 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.> 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:讀鄰近語境
# ==== 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.> 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 meansD 0.802、R 0.798,兩段文字與投影片 90 相同 ✓。注意:D/R 是被查詢的政黨平均向量,不是說話者的政黨;候選池兩黨都有,而且是處理過的語境字,不是完整原文。
互動:924 個 immigration 語境瀏覽器(真實資料)
提示:排「偏 R」再篩說話者=D,可以找到「民主黨議員用了接近共和黨平均的語境」——這就是為什麼一段被挑出的段落不能代表一黨。
C05:embedding regression,固定 gender 比較政黨
# ==== 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.
> 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_R | 8.668 | 8.668 | 10.140 | 0 |
gender_M | 5.155 | 5.155 | 6.909 | 0 |
① party_R 是固定 gender 下共和黨 vs 民主黨的差異向量;和 C02 的未調整平均不同。② p 顯示 0 的意思是「100 次置換中 0 次超過」,不是 p 真的等於 0(≤ 1/100 的量級)。③ 現行 conText 報告去偏後的平方長度,不是 2023 論文的 L2 長度(.175/.087),兩者不能直接比。
E04:把一次觀察、證據和係數接起來
本章小測驗
conText() 吃的 data 是?課堂 R:W9.R 的 security 鄰居、原始語境與 PCA 陷阱
W9/classroom/W9.R 是另一條路線:英國下議院 719 篇黨魁演說(W8 同一份樣本)+老師用這份樣本訓練的 30 維教學 GloVe(1,653 字型)。依 Data/README.md,這個模型只訓練五輪,鄰居「明顯有雜訊」,不是驗證過的語意量測。課堂只做 R00、R05;其他是課後。
R00:套件與檔案
# ==== 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.> 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-26R05:靜態詞向量與原始語境
# ==== 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.
> 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:在 2D 地圖上離 security 最近的是 discussed;但在全部 30 維,cosine 最高的是 resolution(0.661);PC1+PC2 只保留這個模型單位向量 9.54% 的變異。本機重算(export_W9a.R,對單位向量做 prcomp(center = TRUE)):
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 相同 ✓。
security 的原始語境(真實 KWIC,抽 60 筆 / 共 144 筆)
R06:平均已知字向量並報告覆蓋率(課後)
# ==== 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?> 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)
# ==== 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.> 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.75000LIX=每句字數+長字(> 6 字元)百分比,越高越難;Flesch Reading Ease 越高越容易。兩黨中位數:Conservative Flesch 58.22/LIX 42.03,Labour 57.24/42.96。切句子會同時改變兩個分數,政策內容卻沒變。
補充投影片 95–112:manufacturing、評估、情緒量測、可讀性
總統怎麼談 manufacturing?
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(重組、就業)。
替用途驗證表示
| 評估 | 問題 |
|---|---|
| Intrinsic(內在) | 向量關係是否符合外部對字的判斷? |
| Extrinsic(外在) | 向量能不能幫下游任務,例如預測標籤? |
| Substantive(實質) | 這個比較能不能支持研究問題需要的詮釋? |
GRS 2022 §8.4, p. 87。投影片的討論題:manufacturing 的時期對比,要讀哪些段落來檢查?
W10 比較:德國政治文本的情緒量測
Widmann & Wich (2023):9,898 句標註過的議會演說與政黨 Facebook 貼文;三條路線:鄰居擴充的 ed8 字典、word2vec 句子平均+神經網路、微調 ELECTRA。保留句的 F1:
| 模型 | Anger | Fear |
|---|---|---|
| ed8 | .59 | .52 |
| word2vec + NN | .79 | .55 |
| ELECTRA | .84 | .64 |
Table 1, p. 634;作者另用新的隨機句樣本測試,穩健性檢查 pp. 635–638。
依用途評估嵌入
| 向量的用途 | 要檢查什麼 |
|---|---|
| 預測用的特徵 | 保留文本或新語料上的表現 |
| 政治語言的量測 | 人類判斷、原始段落、適當基準 |
| 跨語料比較 | 領域、詞彙覆蓋、跨模型設定的穩定性 |
| 社會聯想 | 目標與屬性字集、來源語料組成、比較的敏感度 |
Rodriguez & Spirling (2022) 比較視窗大小、維度、多次訓練與人類對字詞聯想的判斷(pp. 105–108, 112–113)。
主張判斷題
文獻導讀:三篇指定閱讀
Rodriguez, Spirling & Stewart (2023). Embedding Regression. APSR 117(4): 1255–1274
全文: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
全文:本機拿不到(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
全文: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 頁面下載接受稿。取得全文後可再補上附頁碼的完整導讀卡。
常見陷阱與詞彙表
十個常見陷阱
WordEmbeddings("glove") 是靜態查表;三個 security cosine = 1。
11 字圖只保留 38.24%,W9.R 的 30 維模型只保留 9.54%;2D 最近是 discussed、全維度最近是 resolution。
Rheault & Cochrane 要用 Voteview 驗證(r = 0.918)才這樣讀。
Rodman 的 social–equality 要回去讀段落。
Müller & Proksch:擴充後一致性 .61 → .54。
cr_glove_subset 和 cr_transform 是配對;換自己的向量要配自己的 A。
conText 的一列是一次出現(924 contexts,不是 400 篇)。
只有 C05 的 party_R 固定了 gender。
現行 conText 報去偏平方長度,論文是 L2 長度;資料也不同。
段落只說明對比;估頻率要更廣的樣本。C04 的 D/R 是被查詢的平均向量,不是說話者。
詞彙表
總複習、研究設計與參考文獻
章末測驗(20 題)
用一段話設計嵌入研究
投影片 92 的三步:① 從政治問題和「什麼拿到向量」開始;② 為這個問題選語料、表示法和比較;③ 找出可能改變詮釋的證據。題目:怎麼比較一個政策詞在政黨、時期或立法場域之間的用法?
學習進度
參考文獻
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。