W4:字典與情緒分析(Dictionaries and Sentiment Analysis)
W2 把文字切成 token、做成 DFM;W4 往前一步:先定義要量的概念,再用一份「詞 → 類別」的對照表(dictionary)把文字變成分數,最後拿人工判斷來驗證這個分數到底量到了什麼。
本週學習目標
投影片 2 列了五個目標,前四個對應本教材的四大區塊,第五個接到你自己的期末專題。讀完後回來勾選:
- Measurement:說清楚一個字典分數「打算量什麼」。(第 00、04 章)
- Dictionary construction:用政治文本建立並修訂詞表或片語表。(第 02、03、06 章)
- Scoring:把比對結果變成分數,並解釋分母與「沒有任何比對」的文本。(第 04、05 章)
- Validation:用已發表的證據與人工判斷評估效度。(第 07、08 章)
- Own project:為自己的研究規劃一個字典測量。(第 11、14 章的計畫填寫器)
一個政治學研究問題
本週的引導問題:國會議員什麼時候會用負面的方式描述家戶經濟狀況?例句是「Families cannot afford rent or energy bills.」可以比較的對象包括講者、時期或執政/在野。
關鍵是同時讀兩件事:rent 告訴我們議題(家戶開銷),cannot afford 才是評價(困難)。投影片的提醒:提到 inflation 並不代表議員怎麼評價家戶狀況。
注意力、情緒、立場:三個不同的問題
| 概念 | 問的是 | 投影片例句 |
|---|---|---|
| Issue attention(議題注意力) | 提到了什麼? | This speech discusses energy bills. |
| Sentiment(情緒) | 某件事被怎麼評價? | High energy bills are hurting families. |
| Stance(立場) | 對某個目標採取什麼立場? | I support the government’s price cap. |
描述問題時用的負面字,可能同時伴隨支持某項政策。「負面情緒」不等於「反對」。
一條測量流程
點下面每一步看說明(內容取自投影片 5):
- 找相關句子:家戶所得、生活開銷、負擔能力。
- 編碼評價與其對象:家戶狀況被怎麼描述?
- 對照人工判斷驗證:同時納入字典有比對到與沒比對到的文本。
- 比較講者或時期:被判為負面的相關句子 ÷ 所有相關句子。
投影片 5 也坦白說:今天的課分開練習兩件事——計算議題提及與計算正負面字;要真正回答開場問題,還得把「評價」連到它的「對象」,這一步今天沒有完成。
概念、指標、分數、主張
| 層次 | 具體例子(投影片 6) |
|---|---|
| Construct(概念) | 議員談家戶開銷有多少 |
| Indicator(指標) | 計算 rent、energy bills(一個片語比對)等詞的比對次數 |
| Score(分數) | 演說 A:4 次 / 100 字 = 每百字 4;演說 B:4 / 200 = 每百字 2 |
| Claim(主張) | 每 100 字中,A 的家戶開銷比對次數是 B 的兩倍 |
注意投影片 6 最後一句:這只是在數提及;要量負面評價,還要辨識 cannot afford 這類語言。
同一份語料,不同的分析單位
| 文本單位 | 對應的政治學問題 |
|---|---|
| Sentence(句子) | 哪些陳述在講家戶困難? |
| Speech(一次發言) | 一次發言有多少比例在談困難? |
| Speaker-period(講者 × 時期) | 某位講者的注意力如何隨時間改變? |
本週練習資料:5,000 筆英國下議院(House of Commons)發言,1945–2025(Data/hc_sample_1945_2025.rds)。切分或合併文本時,要保留講者、日期與來源 ID。
練習:這句話在量哪一種概念?
每句選一個:議題注意力、情緒、立場。(例句改寫自投影片 3–4 與 66 的概念;判斷理由會在作答後顯示。)
怎麼使用本教材
- 每章右側(寬螢幕)或右下角按鈕(手機)是投影片對照;捲到標有「投影片 N」的段落會自動翻頁。
- R 程式碼取自
W4/classroom/W4_classroom.R(C01–C16)與課後W4/lab/Lab_Session_W4.R;所有輸出都是本機實際執行的結果(R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64),並逐一對照投影片數字。 - 互動元件分三類:真實資料(用本週 Data/ 匯出)、玩具直覺(標「補充(非講義內容)」)、練習(作答區、翻牌卡、主張判斷、計畫填寫器)。
- 進度、作答只存在這台瀏覽器;側欄可看完成度。
Bag of words、DFM 與字典
字典方法建立在 W2 的 bag-of-words 之上:文件被拆成 token、數成一張文件 × 特徵的表(DFM)。這一章先跑 C01 載入資料,再用兩句話的小例子看清楚 DFM、文件長度與字典比對。
C01:一次設定,整堂課共用
每份文件是一次國會發言(speech contribution)。C01 會找到 workflow.R、切換工作目錄並 source() 它;workflow.R 一口氣準備好後面要用的物件:speeches、discovery_tokens、comparison、check_scores、policy_scores、validation 等。之後保持同一個 R session。
# C01: Setup
# First use: uncomment the next line to install.
# install.packages(c("quanteda", "quanteda.textstats"))
library(quanteda)
library(quanteda.textstats)
paths <- c("workflow.R", "W4/classroom/workflow.R",
"classroom/workflow.R", "../classroom/workflow.R")
found <- paths[file.exists(paths)]
if (length(found) == 0) found <- file.choose()
setwd(dirname(normalizePath(found[1])))
source("workflow.R")> library(quanteda)
Package version: 4.5.1
Unicode version: 17.0
ICU version: 78.3
Parallel computing: 2 of 2 threads used.
See https://quanteda.io for tutorials and examples.
> library(quanteda.textstats)
> paths <- c("workflow.R", "W4/classroom/workflow.R",
+ "classroom/workflow.R", "../classroom/workflow.R")
> found <- paths[file.exists(paths)]
> if (length(found) == 0) found <- file.choose()
> setwd(dirname(normalizePath(found[1])))
> source("workflow.R")- 讀
hc_sample_1945_2025.rds(檢查 5,000 列、沒有缺文字),給每篇speech_0001… 的 ID。 toks:去標點、轉小寫;lengths_original= 每篇 token 數,之後所有「每百字」「每千字」的分母都用它。policy_tokens:保留標點的另一條 token 流,專門拿來比對片語,避免片語跨過句號。- 用固定種子
set.seed(719104)抽 80 篇做人工編碼範本(30 development + 50 test);discovery_tokens= 扣掉 50 篇 test 之後的 4,950 篇。找詞只用 discovery,測試留給 test(第 02 章末、第 07 章)。
C02:計數與文件長度
先預測:A 這列的 prices 會是幾?
# C02: Counts and document length
library(quanteda)
demo <- c(A = "Prices rise. Prices worry voters.",
B = "Prices fall.")
demo_tokens <- tokens(demo, remove_punct = TRUE)
demo_dfm <- dfm(demo_tokens)
selected <- dfm_match(demo_dfm, c("prices", "rise", "fall"))
as.matrix(selected)
ntoken(demo_tokens)> library(quanteda)
> demo <- c(A = "Prices rise. Prices worry voters.",
+ B = "Prices fall.")
> demo_tokens <- tokens(demo, remove_punct = TRUE)
> demo_dfm <- dfm(demo_tokens)
> selected <- dfm_match(demo_dfm, c("prices", "rise", "fall"))
> as.matrix(selected)
features
docs prices rise fall
A 2 1 0
B 1 0 1
> ntoken(demo_tokens)
A B
5 2 - 列 = 文件;欄 = 選出來的字;每格是出現次數。A 列:prices 2 次、rise 1 次、fall 0 次。
- 長度不一樣:A 有 5 個 token,但表上只顯示 3 次——
worry和voters沒被選進來。這就是後面「分母要用全部 token」的伏筆。 dfm()預設轉小寫,所以Prices與prices是同一欄。
互動:自己做一張 DFM
補充(非講義內容):這裡的切字規則是簡化版(以空白與標點切開),對英文短句與 quanteda 結果一致,但不處理連字號、縮寫等細節。
字數表丟掉了什麼
The government does not support the opposition.
The opposition does not support the government.
同一袋字,誰對誰完全相反。這也是為什麼 W4 之後要談片語(第 03 章)、否定(第 05 章)與「情緒 ≠ 立場」(第 08 章)。在上面的互動元件把兩句貼進 A、B、清空特徵欄,就會看到兩列完全相同。
什麼是字典?
字典把「表達方式」對應到事先定義好的類別。quanteda 的寫法:
library(quanteda)
dic <- dictionary(list(
household_costs = c("inflation", "rent", "energy bills"),
employment = c("unemployment", "job security")
))投影片 12:提到家戶開銷,不代表就證明了經濟困難。
套用我們的字典
老師把投影片 12–13 合成一個可獨立執行的檔案 examples/W4_dictionary_simple.R。本機執行結果:
> library(quanteda)
> dic <- dictionary(list(
+ household_costs = c("inflation", "rent", "energy bills"),
+ employment = c("unemployment", "job security")
+ ))
> texts <- c("Rent and energy bills are rising.",
+ "We need job security.")
> example_tokens <- tokens(texts, remove_punct = FALSE)
> matched <- tokens_lookup(example_tokens, dic, capkeys = FALSE)
> counts <- dfm(matched)
> as.matrix(counts)
features
docs household_costs employment
text1 2 0
text2 0 1rent + energy bills 給 2 次比對;job security 給 1 次。注意 energy bills 是片語:tokens_lookup() 會在 token 序列上找連續兩個字,算一次。與投影片 13 的表一致。
ntoken() 是 5。原因?找候選詞:頻率、KWIC、搭配詞、keyness
字典可以沿用、改編或自建,但「現成的」不等於「合適的」。這一章跑 C03–C06,用四種工具從 4,950 篇 discovery 發言裡找候選詞,並且每一步都回去讀上下文。
沿用、改編,還是自建?
| 選擇 | 主要問題 |
|---|---|
| 現成字典(Existing) | 它原本的領域適合這份語料嗎? |
| 改編字典(Adapted) | 哪些修改在這裡能改善表現? |
| 自建字典(New) | 我們能記錄涵蓋範圍與排除規則嗎? |
| 改用其他方法 | 這個類別是否太依賴語境,字詞規則撐不住? |
投影片 14:Availability is not evidence of suitability。Grimmer & Stewart(2013, pp. 274–275)引 Loughran & McDonald(2011)的例子:tax、cost、crude(oil)、cancer 在其他脈絡帶負面意涵,在公司財報裡卻可能帶正面意涵(見第 12 章導讀)。
建立或改編詞表的四步
- 寫下什麼該算,並附一個不該算的例子。
- 閱讀有談與沒談該議題的段落。
- 列出代表該議題的字與片語。
- 檢查誤比對(false matches)與詞表漏掉的相關段落。
以家戶開銷為例:要分辨 energy bills(帳單)和國會的 bill(法案)。
C03:頻率——出現次數 vs 出現在幾篇
# C03: Frequency in real speeches (run C01 first)
recap_dfm <- dfm(discovery_tokens)
recap_dfm <- dfm_remove(recap_dfm, stopwords("en"))
# Keep words made of English letters only.
recap_dfm <- dfm_select(recap_dfm, "^[a-z]+$", valuetype = "regex")
freq <- textstat_frequency(recap_dfm)
head(freq, 6)> recap_dfm <- dfm(discovery_tokens)
> recap_dfm <- dfm_remove(recap_dfm, stopwords("en"))
> # Keep words made of English letters only.
> recap_dfm <- dfm_select(recap_dfm, "^[a-z]+$", valuetype = "regex")
> freq <- textstat_frequency(recap_dfm)
> head(freq, 6)
feature frequency rank docfreq group
1 hon 6514 1 2826 all
2 government 3190 2 1320 all
3 right 2762 3 1470 all
4 member 2395 4 1129 all
5 can 2391 5 1221 all
6 people 2273 6 995 allfrequency:總出現次數;docfreq:有出現的發言篇數;rank依 frequency 排序;group = all表示全部發言合併計算。- 本機結果與投影片 17 完全一致:hon 6,514 次、出現在 2,826 篇。
- 練習:把 6 改成 12,哪些字是在描述議事程序而不是政策?(hon、right、member 是「the right hon. Member」這種稱呼。)
C04:KWIC——把字放回上下文
KWIC = keyword in context。security 一定指國防嗎?
# C04: Context in real speeches (run C01 first)
live_contexts <- kwic(discovery_tokens, "security", window = 5)
context_table <- as.data.frame(live_contexts)
columns <- c("docname", "pre", "keyword", "post")
head(context_table[, columns], 2)> live_contexts <- kwic(discovery_tokens, "security", window = 5)
> context_table <- as.data.frame(live_contexts)
> columns <- c("docname", "pre", "keyword", "post")
> head(context_table[, columns], 2)
docname pre keyword post
1 speech_0024 as a basis of international security , is essential to the
2 speech_0246 raise the question in the security council . we advanced £每列是一次比對;從 pre → keyword → post 橫著讀,左右各最多 5 個 token。第 1 列是 international security,第 2 列是 security council——同一個字,兩種意思。
資料說明:本機用 kwic(discovery_tokens, pattern, window = 8) 匯出;比對超過 150 次的字隨機抽 150 列(set.seed(4))。
C05:搭配詞——候選片語
Collocation:相鄰且統計上強烈相關的兩個字。依 lambda 由大到小排序。
# C05: Phrases in real speeches (run C01 first) coll <- textstat_collocations(discovery_tokens, size = 2, min_count = 20) row_order <- order(coll$lambda, decreasing = TRUE) coll <- coll[row_order, ] head(coll, 6) first_phrase <- phrase(coll$collocation[1]) phrase_context <- kwic(discovery_tokens, first_phrase, window = 5) head(phrase_context, 2)
> coll <- textstat_collocations(discovery_tokens, size = 2, min_count = 20)
> row_order <- order(coll$lambda, decreasing = TRUE)
> coll <- coll[row_order, ]
> head(coll, 6)
collocation count count_nested length lambda z
2809 sri lanka 23 0 2 15.65685 10.56449
2692 per cent 718 0 2 15.64201 11.04304
1743 dispatch box 23 0 2 13.23135 15.27786
1283 liberal democrats 37 0 2 12.40680 18.59108
113 northern ireland 334 0 2 12.22301 51.32513
452 united kingdom 300 0 2 11.97618 29.83622
> first_phrase <- phrase(coll$collocation[1])
> phrase_context <- kwic(discovery_tokens, first_phrase, window = 5)
> head(phrase_context, 2)
Keyword-in-context with 2 matches.
[speech_1885, 29:30] the british-owned tea estates in | sri lanka | . there has been considerable
[speech_1885, 80:81] to extend its stay in | sri lanka | to investigate the conditions of- 排第一的是 sri lanka;兩次比對都來自同一篇 speech_1885。
- 強搭配詞只是候選:地名本身不能量家戶開銷。
C06:Keyness——比較兩群
# C06: Relative word use (run C01 and C03 first)
party_dfm <- dfm_subset(recap_dfm,
party %in% c("Conservative", "Labour"))
party_dfm <- dfm_group(party_dfm, groups = party)
party_dfm <- dfm_trim(party_dfm, min_termfreq = 1)
keys_con <- textstat_keyness(party_dfm, target = "Conservative")
keys_lab <- textstat_keyness(party_dfm, target = "Labour")
head(keys_con, 3)
head(keys_lab, 3)> party_dfm <- dfm_subset(recap_dfm,
+ party %in% c("Conservative", "Labour"))
> party_dfm <- dfm_group(party_dfm, groups = party)
> party_dfm <- dfm_trim(party_dfm, min_termfreq = 1)
> keys_con <- textstat_keyness(party_dfm, target = "Conservative")
> keys_lab <- textstat_keyness(party_dfm, target = "Labour")
> head(keys_con, 3)
feature chi2 p n_target n_reference
1 aircraft 44.37288 2.714218e-11 116 31
2 cyberstalking 39.62479 3.077519e-10 42 0
3 stalking 33.96359 5.615304e-09 36 0
> head(keys_lab, 3)
feature chi2 p n_target n_reference
1 waste 61.43017 4.551914e-15 124 31
2 tory 49.50067 1.983080e-12 73 11
3 advertising 38.71565 4.902623e-10 64 12| Target: Conservative(投影片 23) | Target: Labour | ||||||
|---|---|---|---|---|---|---|---|
| Word | chi2 | Con. | Lab. | Word | chi2 | Con. | Lab. |
| aircraft | 44.37 | 116 | 31 | waste | 61.43 | 31 | 124 |
| cyberstalking | 39.62 | 42 | 0 | tory | 49.50 | 11 | 73 |
| stalking | 33.96 | 36 | 0 | advertising | 38.72 | 12 | 64 |
- 兩個 target 各跑一次,每個表顯示該黨前三個正 keyness 分數。
- keyness 考慮了每群的 token 總數——光看次數不能決定。
- 這些字是這份樣本中的特徵詞,不一定最常見,也跟情緒正負無關。
把「找詞」和「評估」分開
- 記錄字典版本與納入規則。
- 不要在最終評估樣本上繼續調整。
- 語言或時期改變時要重新檢查表現。
對應到程式:workflow.R 把 50 篇 test 發言從 discovery_tokens 拿掉,所以 C03–C06 找詞時根本看不到它們。
比對規則:片語與萬用字元
同一個概念可以寫成很多種規則:寬的 bill*、精確的 bill/bills、片語 energy bills。規則越寬,誤比對越多;規則越窄,漏掉越多。
一個可以手算的小例子
| 文本 | 寬規則 bill* | 片語 energy bills |
|---|---|---|
| Energy bills are rising. | 1 | 1 |
| This bill reforms parliament. | 1 | 0 |
| Families cannot afford heating. | 0 | 0 |
改用片語去掉了一個 false positive(法案),但仍然漏掉一個相關段落(買不起暖氣)。
C07:用 quanteda 比對片語
# C07: A complete phrase-lookup example
library(quanteda)
examples <- c("Energy bills are rising.",
"This bill reforms parliament.",
"Families cannot afford heating.")
example_tokens <- tokens(examples, remove_punct = FALSE)
cost_dict <- dictionary(list(costs = "energy bills"))
matched <- tokens_lookup(example_tokens, cost_dict)
cost_counts <- dfm(matched)
as.matrix(cost_counts)> library(quanteda)
> examples <- c("Energy bills are rising.",
+ "This bill reforms parliament.",
+ "Families cannot afford heating.")
> example_tokens <- tokens(examples, remove_punct = FALSE)
> cost_dict <- dictionary(list(costs = "energy bills"))
> matched <- tokens_lookup(example_tokens, cost_dict)
> cost_counts <- dfm(matched)
> as.matrix(cost_counts)
features
docs costs
text1 1
text2 0
text3 0預測對了嗎?只有第一句被比對到(1, 0, 0)。投影片的練習:在字典裡加 "cannot afford heating"——哪種錯誤會改變?(第三句的 false negative 被修好了,但這個片語非常具體,換個說法就又漏掉。)下面的測試台可以直接試。
C08:萬用字元 vs 精確比對
# C08: Wildcards in real speeches (run C01 first)
wild <- kwic(discovery_tokens, "bill*", window = 0)
exact <- kwic(discovery_tokens, c("bill", "bills"),
valuetype = "fixed", window = 0)
c(wildcard = nrow(wild), exact = nrow(exact))
word_counts <- table(wild$keyword)
word_counts <- sort(word_counts, decreasing = TRUE)
head(word_counts, 8)> wild <- kwic(discovery_tokens, "bill*", window = 0)
> exact <- kwic(discovery_tokens, c("bill", "bills"),
+ valuetype = "fixed", window = 0)
> c(wildcard = nrow(wild), exact = nrow(exact))
wildcard exact
1774 1539
> word_counts <- table(wild$keyword)
> word_counts <- sort(word_counts, decreasing = TRUE)
> head(word_counts, 8)
bill billion bills bill's billions billericay bill’s billâ
1470 157 69 24 18 5 3 3 bill*會比對 bill 後面接任何字尾,包括 billion、billericay(地名)。- 精確
bill/bills:1,470 + 69 = 1,539。 - 精確比對仍然把「法案」和「家戶帳單」混在一起——它解決不了語意上的歧義。
- 輸出裡看得到不同的撇號(bill's 與 bill’s)以及疑似編碼殘留(billâ)。這些是比對次數,不是篇數。
互動:規則測試台
補充(非講義內容):比對邏輯模仿 tokens_lookup() 的 glob 規則(不分大小寫、* 代表任意字尾、片語須連續出現、保留標點時片語不能跨過句號)。
片語規則保留有用的脈絡
- 片語能分出能源帳單與立法法案。
- 越長的 n-gram 帶有越多在地脈絡。
- 但越具體的表達也越罕見。
- 先比對片語,再移除停用詞——不然 cannot afford 之類的片語可能先被拆壞。
投影片 29 的圖(Hvitfeldt & Silge 2022):每個點是一篇 Andersen 童話在某個 n-gram 長度下的不同 n-gram 數;n 越大,最常見的 n-gram 次數越少(顏色越紫)。
分母、情緒分數與「零」
比對完之後要變成數字。這一章談三件事:除以什麼(C09)、兩種情緒摘要(net tone 與 coverage)、以及零分不一定是中性(C10)。
C09:文件長度與分母
預測:用「次數」與用「比率」排出來的前幾名會一樣嗎?
# C09: Rankings on real speeches (run C01 first)
discovery_ids <- docnames(discovery_tokens)
rates <- subset(comparison, doc_id %in% discovery_ids)
rates <- subset(rates, tokens >= 50)
cols <- c("doc_id", "broad", "tokens", "broad_per100")
raw_order <- order(rates$broad, decreasing = TRUE)
rate_order <- order(rates$broad_per100, decreasing = TRUE)
head(rates[raw_order, cols], 3)
head(rates[rate_order, cols], 3)> discovery_ids <- docnames(discovery_tokens)
> rates <- subset(comparison, doc_id %in% discovery_ids)
> rates <- subset(rates, tokens >= 50)
> cols <- c("doc_id", "broad", "tokens", "broad_per100")
> raw_order <- order(rates$broad, decreasing = TRUE)
> rate_order <- order(rates$broad_per100, decreasing = TRUE)
> head(rates[raw_order, cols], 3)
doc_id broad tokens broad_per100
speech_2792 speech_2792 20 1349 1.4825797
speech_1673 speech_1673 19 2655 0.7156309
speech_0743 speech_0743 18 1599 1.1257036
> head(rates[rate_order, cols], 3)
doc_id broad tokens broad_per100
speech_4435 speech_4435 4 69 5.797101
speech_1551 speech_1551 4 78 5.128205
speech_4917 speech_4917 3 59 5.084746- Rate = 100 × broad / tokens;broad 是
bill*的比對次數。 - 20 / 1,349 → 每百字 1.48;4 / 69 → 每百字 5.80。比對次數多,不代表密度高。
- 本機輸出的六列與投影片 31 完全相同。
兩種簡單的情緒摘要
令 P = 正面比對數、N = 負面比對數、L = 原始 token 數。
| 摘要 | 定義 | 解讀 |
|---|---|---|
| Net tone | 100 × (P − N) / L | 每 100 個 token 的淨比對數 |
| Match coverage | 100 × (P + N) / L | 每 100 個 token 中被比對到的情緒 token |
P = 3、N = 1、L = 100:net tone = 2,coverage = 4%。投影片也預告:後面 Proksch et al. 的案例用的是另一種計分規則(第 08 章)。
C10:零不一定是中性
check_texts 是 workflow.R 建的五個教學例子;情緒字典是十個字的 Dictionaries/teaching_affect.dic(positive:good、excellent、success、successful、improve;negative:bad、failure、crisis、harm、harmful)。
# C10: Zero, balance and missing matches
check_texts
check_scores[, c("doc_id", "positive", "negative",
"net_per100", "coverage_per100", "balance")]> check_texts
good negated unmatched
"The policy is good." "The policy is not good." "The minister spoke today."
balanced empty
"A good plan with a bad outcome." ""
> check_scores[, c("doc_id", "positive", "negative",
+ "net_per100", "coverage_per100", "balance")]
doc_id positive negative net_per100 coverage_per100 balance
1 good 1 0 25 25.00000 1
2 negated 1 0 20 20.00000 1
3 unmatched 0 0 0 0.00000 NA
4 balanced 1 1 0 28.57143 0
5 empty 0 0 NA NA NA| doc_id | 發生什麼事(投影片 34) |
|---|---|
| good | 1 個正面比對 / 4 字 → 每百字 25;所有比對都是正面,balance = 1。 |
| negated | 1 個正面比對 / 5 字 → 20。規則忽略了 not。 |
| unmatched | 有文字但 P = N = 0;balance 的分母是 0 → NA。 |
| balanced | P = N = 1、共 7 字:net = 0,coverage = 100 × 2 / 7 = 28.57%。 |
| empty | L = 0 且 P + N = 0:三個分數都無定義(NA)。 |
零可以代表「沒比對到」也可以代表「正負相抵」;兩者都不能證明中性。
未勾選時,計算方式與 workflow.R 的 score_sentiment() 相同(去標點、轉小寫、分母為全部 token;分母為 0 時給 NA)。最後一行空白對應 empty。勾選的否定規則是補充(非講義內容),用來對照第 05 章「固定否定視窗的限制」。
否定詞、前處理與 Denny & Spirling
bag-of-words 字典不懂「not good」。保留 not 只是第一步,還需要一條用到它的規則;而每個前處理選擇(停用詞、詞形)都可能改變結果——Denny & Spirling 的宣言案例顯示,128 種前處理組合會排出 12 種不同順序。
C11:一個刻意的情緒失敗
預測:保留 not 會讓第二句變成負面嗎?
# C11: A deliberate sentiment failure (run C01 first)
negation_tokens <- check_tokens[c("good", "negated")]
as.list(negation_tokens)
negation_dfm <- dfm(negation_tokens)
negation_counts <- dfm_lookup(negation_dfm, toy_sentiment)
as.matrix(negation_counts)
without_stopwords <- tokens_remove(negation_tokens, stopwords("en"))
as.list(without_stopwords)> negation_tokens <- check_tokens[c("good", "negated")]
> as.list(negation_tokens)
$good
[1] "the" "policy" "is" "good"
$negated
[1] "the" "policy" "is" "not" "good"
> negation_dfm <- dfm(negation_tokens)
> negation_counts <- dfm_lookup(negation_dfm, toy_sentiment)
> as.matrix(negation_counts)
features
docs positive negative
good 1 0
negated 1 0
> without_stopwords <- tokens_remove(negation_tokens, stopwords("en"))
> as.list(without_stopwords)
$good
[1] "policy" "good"
$negated
[1] "policy" "good" - 字典比對:兩句都比對到 good(positive = 1、negative = 0)。規則沒有用 not 來反轉。
- 移除停用詞之後:
not在stopwords("en")裡,被刪掉了;兩句的 token 變得一模一樣:"policy" "good"。
保留否定詞,然後加一條處理它的規則。
互動:一個固定的否定視窗能做到哪裡?
句子取自投影片 37 的四種困難情況,外加 C11 的兩句。字典=teaching_affect.dic 加上 reject(負面,為了示範第二句而加,非講義字典內容)。Rauh(2018)的做法是「直接的兩字否定規則」(投影片 57);這裡的視窗=1 最接近它。
固定否定視窗的限制
- 「Not good」和「not only good but excellent」不一樣。
- 「I reject the claim that this is a failure」含有負面字。
- 引述別人的批評,不一定是講者自己的看法。
- 長距離的否定可能超出簡單的字數視窗。
規則能改善基準線,但不能解決每一句。
前處理必須配合字典
- 不同停用詞表會刪掉文本中不同比例的字。
- 否定詞有意義時要保留。
- 字典條目要對齊你選擇的詞形(例如有沒有 stemming/lemmatisation)。
- 檢查每個前處理選擇丟掉了什麼。
投影片 38 的圖(Hvitfeldt & Silge 2022):每篇故事三個點、對應三份停用詞表;X = 總字數、Y = 被移除字詞的百分比。同一份文本,不同表移除的比例不同。
案例:從宣言定位政黨(Denny & Spirling 2018)
- 問題:宣言用語能把政黨放在左右量尺上嗎?資料:8 份英國政黨宣言,1983–1997;模型:Wordfish(從字數估計位置)。
- 同樣 8 份宣言、同一個 Wordfish 模型,128 種前處理規格,排出12 種不同的文件順序;黑色格子=與作者事前排序不一致。
| 研究主張 | 這個案例能顯示什麼(投影片 41) |
|---|---|
| 字彙可以把政黨放上量尺 | Wordfish 從字數估計相對位置 |
| 排序在合理選擇下穩健 | 要檢查:這個例子產生 12 種排序 |
| 模型解釋政黨為何改變 | 這是因果問題,需要不同的研究設計 |
帶回字典:實質比較在合理的計分選擇下還站得住嗎?(下一章 C12/C15 就是在做這件事。)
tokens_remove(stopwords("en")) 後會怎樣?字典修訂與敏感度(C12、C15)
這一章的研究構念換成能源政策注意力(不是情緒)。Dictionaries/energy_policy.csv 有兩個版本:v1 寬、v2 窄。改字典會改分數——但改了之後是不是更好,只有人工判斷能回答。
C12:字典修訂改善了測量嗎?
先預測:哪個版本會標記更多發言?
# C12: Dictionary revisions (run C01 first)
policy_entries[, c("version", "category", "pattern")]
dev <- subset(policy_scores,
doc_id %in% docnames(discovery_tokens))
c(v1 = sum(dev$v1 > 0), v2 = sum(dev$v2 > 0))
energy_context <- kwic(discovery_tokens, "energy", window = 5)
head(energy_context, 3)> policy_entries[, c("version", "category", "pattern")]
version category pattern
1 v1 energy energy
2 v1 energy power
3 v1 energy electric*
4 v1 energy gas
5 v1 energy bill*
6 v2 energy energy
7 v2 energy electric*
8 v2 energy gas bill*
9 v2 energy renewab*
10 v2 energy solar*
11 v2 energy wind farm*
12 v2 energy fossil fuel*
> dev <- subset(policy_scores,
+ doc_id %in% docnames(discovery_tokens))
> c(v1 = sum(dev$v1 > 0), v2 = sum(dev$v2 > 0))
v1 v2
899 139
> energy_context <- kwic(discovery_tokens, "energy", window = 5)
> head(energy_context, 3)
Keyword-in-context with 3 matches.
[speech_0103, 105] production and use of atomic | energy | , clause 10 enables him
[speech_0103, 134] , 521 or of atomic | energy | plant. it is thought
[speech_0105, 2610] , the will and the | energy | to push it through, | v1(寬) | v2(窄) |
|---|---|
energy、power、electric*、gas、bill* | energy、electric*、gas bill*、renewab*、solar*、wind farm*、fossil fuel* |
- v2 拿掉了最歧義的
power(政治權力)、gas(催淚瓦斯)、bill*(法案),把 gas 收窄成片語gas bill*,並加上再生能源相關詞。 - 結果寫在下面的輸出:
v1 = 899 篇、v2 = 139 篇(4,950 篇中至少一次比對)。分數變了——但這是否更接近人工判斷?投影片 42 的討論題就是這個。 - KWIC 的前 3 列能直接看到
energy也可能是「精力」的意思。
互動:在真實發言上比較 v1 與 v2 的螢光筆
樣本:本機以 set.seed(719) 從 discovery 發言中抽 300 篇(60–700 tokens),再加入 v2 每千字比對最高的 40 篇(≤ 900 tokens)以確保有能源相關發言,去重後 335 篇——不是隨機樣本,不能拿來估計全語料的 precision。比對邏輯同第 07 章驗證台(JS 模仿 tokens_lookup());每千字比率的分母用 JS 的切字數,與 R 的 tokens 欄可能有小差異,下方同時列出 R 的 token 數。
C15:視覺化字典敏感度
dev 是 C12 建的表:一列一篇發言,共 4,950 篇;v1_per1000、v2_per1000 是兩個版本每千字的比對數。
# C15: Visualizing dictionary sensitivity (run C12 first)
# install.packages("ggplot2") # run once
library(ggplot2)
ggplot(dev, aes(x = v1_per1000, y = v2_per1000)) +
geom_point(size = 1, alpha = 0.4, colour = "#314f4f") +
geom_abline(intercept = 0, slope = 1,
colour = "firebrick", linetype = "dashed") +
labs(x = "v1 matches per 1,000 tokens",
y = "v2 matches per 1,000 tokens") +
theme_minimal()重疊的點可能藏住很多篇。分數改變顯示的是敏感度,不是哪一版更有效度。
延伸:用 v1/v2 比較政黨(Lab 選做段落)
workflow.R 也算了政黨層級的比率:先加總、再相除(ratio of group totals),不是每篇比率的平均。注意 party_rates 用的是全部 5,000 篇(policy_scores),不只是 4,950 篇 discovery。
人工基準、kappa、precision/recall
驗證要有人工判斷當基準。這一章先看人與人之間一致嗎(C13,kappa),再看字典和人一致嗎(C14,precision/recall/F1),最後用 24 句教學句子實作「開發 → 凍結 → 測試」。
人工基準
- 寫一份 codebook,附正面、負面與模糊的例子。
- 可行時,讓編碼者不知道字典的預測。
- 記錄分歧與裁決程序。
- 編碼單位要對齊分數的用途。
人工標記是要被檢視的證據,不是不容質疑的真相。
該驗證哪些文本?
- 同時納入有比對與沒比對的段落。
- 涵蓋重要日期、群體與不同長度的文件。
- 最終表現估計要用沒碰過的樣本。
- 罕見或模糊的案例另外檢查,用於診斷。
一堆簡單例子不能建立全語料的表現。
C13:兩位人工編碼者的一致性
# C13: Human agreement, not model accuracy
# install.packages("irr") # run once
library(irr)
ratings <- data.frame(
coder_A = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0),
coder_B = c(1, 1, 1, 1, 0, 1, 0, 0, 0, 0))
table(ratings$coder_A, ratings$coder_B)
mean(ratings$coder_A == ratings$coder_B)
agreement <- kappa2(ratings, weight = "unweighted")
agreement$value> library(irr)
Loading required package: lpSolve
> ratings <- data.frame(
+ coder_A = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0),
+ coder_B = c(1, 1, 1, 1, 0, 1, 0, 0, 0, 0))
> table(ratings$coder_A, ratings$coder_B)
0 1
0 4 1
1 1 4
> mean(ratings$coder_A == ratings$coder_B)
[1] 0.8
> agreement <- kappa2(ratings, weight = "unweighted")
> agreement$value
[1] 0.6原始一致率 80%(10 個中 8 個相同),Cohen’s kappa = 0.60。kappa 扣掉了「兩人都隨便猜也會一樣」的機率:這裡兩人各標了 5 個 1、5 個 0,偶然一致的期望值是 0.5,所以 κ = (0.8 − 0.5) / (1 − 0.5) = 0.6。
補充(非講義內容):試著讓兩人都把幾乎所有文本標成 0(例如 0, 1, 1, 18)——一致率很高,但 kappa 會掉很多。
議題偵測的混淆矩陣
| 20 個示範段落 | 人工:相關 | 人工:不相關 |
|---|---|---|
| 字典:有比對 | 6 true positives | 2 false positives |
| 字典:沒比對 | 4 false negatives | 8 true negatives |
單位是段落,不是字典裡的字。
C14:precision 與 recall
跑程式前先用上面的表手算一次。
# C14: Checking validation arithmetic (run C01 first) predicted <- validation$predicted human <- validation$human TP <- sum(predicted == 1 & human == 1) FP <- sum(predicted == 1 & human == 0) FN <- sum(predicted == 0 & human == 1) precision <- TP / (TP + FP) recall <- TP / (TP + FN) F1 <- 2 * TP / (2 * TP + FP + FN) c(precision = precision, recall = recall, F1 = F1)
> predicted <- validation$predicted > human <- validation$human > TP <- sum(predicted == 1 & human == 1) > FP <- sum(predicted == 1 & human == 0) > FN <- sum(predicted == 0 & human == 1) > precision <- TP / (TP + FP) > recall <- TP / (TP + FN) > F1 <- 2 * TP / (2 * TP + FP + FN) > c(precision = precision, recall = recall, F1 = F1) precision recall F1 0.7500000 0.6000000 0.6666667
- Precision = 0.75:字典標記的 8 段中,6 段相關(6 / 8)。
- Recall = 0.60:10 段相關的裡面,字典找到 6 段(6 / 10)。
- F1 ≈ 0.667:2 × 6 / (2 × 6 + 2 + 4)。
漏掉的案例很重要:只讀字典比對到的段落,無法得知 recall。
試試看投影片 49 的問題:如果只讀字典有比對的 TP + FP 段落,你能算出 FN 嗎?
互動:開發 → 凍結 → 測試(24 句教學句子)
Data/synthetic_validation.csv 有 24 句老師撰寫的教學句子與標記(12 句 development、12 句 test;1 = 能源政策相關)。這不是真實國會發言,也不是獨立觀察到的人工標記(workflow.R 的註解)。投影片 95 的步驟:
- Develop:用 12 句開發句看 v1、v2 錯在哪。
- Freeze:在下一組 12 句上保持 v2 不變。
- Test:把預測和標記比對,包括沒比對到的句子。
- Result:precision 0.80、recall 0.667、F1 0.727。只是示範用的算術,不是在國會語料上的表現估計。
print(synthetic_results):workflow.R 用同一組 v1/v2 在 development 與 test 上的結果)n tp fp fn tn precision recall f1 accuracy split version 1 12 3 4 3 2 0.4285714 0.5000000 0.4615385 0.4166667 development v1 2 12 6 1 0 5 0.8571429 1.0000000 0.9230769 0.9166667 development v2 3 12 4 4 2 2 0.5000000 0.6666667 0.5714286 0.5000000 test v1 4 12 4 1 2 5 0.8000000 0.6666667 0.7272727 0.7500000 test v2
比對邏輯:保留標點、不分大小寫、glob 萬用字元、片語須連續(模仿 policy_counts());載入 v1/v2 時,每句的預測會與 R 實跑結果核對,表格最右欄顯示「R」的預測。
評估連續的情緒分數
- 把分數對人工評分畫圖。
- 檢查群組平均與個別分歧。
- 檢查沒比對到的文本、被壓縮的範圍與極端值。
- 比較不同群體與文類下的表現。
驗證要對應主張的層次
| 主張 | 需要的證據 |
|---|---|
| 這一句是負面的 | 句子層級的一致性 |
| 這一群相對比較正面 | 群體層級的測量效度 |
| 情緒隨時間改變 | 跨時期穩定的測量 |
| 各國衝突程度不同 | 可比較的測量與制度脈絡 |
案例:Boyle、Rauh、Proksch
三個已發表研究,各自示範字典測量的一個環節:自建字典+留出樣本測試(Boyle et al. 2025)、改編字典+人工驗證(Rauh 2018)、翻譯字典+群體層級驗證+實質分析(Proksch et al. 2019)。以下內容皆依投影片整理(三篇全文不在 repo 內,見第 12 章)。
能源研究的政策相關性(Boyle et al. 2025)
- 問題:哪些摘要在傳達政策相關性?資料:270,537 篇摘要、100 份期刊、2010–2023;用自訂字典辨識相關陳述。表達的相關性 ≠ 政策實際採用。
- 單位:一篇摘要(是否含政策相關陳述)。開發:從政策詞開始,讀 400 篇雙人編碼摘要找出更多詞;精修:只保留能提升開發集正類 F1 的新增詞;測試:在另外 200 篇人工編碼、未參與調整的摘要上評估。
- 報告的平均 F1:開發 0.90/留出 0.86。老師的研究過程註記:一開始試過 fine-tune transformers,結果不理想。
- 約 15% 摘要被分類為政策相關;只有 8% 明確提到 policy/policies。期刊宗旨明確提到政策者:26.7%;沒有提到者:3.7%。這是描述性的文本型態,不是政策採用的證據。
對照第 02 章投影片 24:這正是「discovery → 凍結 → held-out」的實際研究版本。開發集 F1 比留出集高,是預期中的現象。
德國政治語言的情緒字典(Rauh 2018)
| 步驟 | 研究做了什麼(投影片 57) |
|---|---|
| Dictionary | 合併 SentiWS 與 GermanPolarityClues;人工審查詞條 |
| Context | 加上直接的兩字否定規則 |
| Score | 正面減負面比對數,除以保留的詞數 |
| Validation | 三人編碼 1,500 句抽樣的 Bundestag 句子 |
- 編碼者一致性:3 位編碼者、1,500 句;完全一致 59.1%;ordinal alpha .675。一致性不等於效度。
- 比較三個字典在人工評分類別上的分數;正面類別分得比較開。區間顯示的是群組平均的不確定性,不是分類準確率。
- 結果:正面評價比負面評價容易還原。用途:比較政治文本中評價語言的已檢驗指標。限制:分數集中在 0 附近,沒有不證自明的數值單位。這個研究驗證的是測量,不解釋政治人物為何變得更正面。
情緒與立法共識(Proksch et al. 2019)
問題:在野黨的語氣是否反映跨黨共識?更正面的在野黨語言是否與法案無異議通過相關?
- 蒐集約 26,000 篇演說,涉及 871 個德國政府法案,2005–2017。
- 用翻譯的 Lexicoder 情緒字典比對正負面字。
- 依政黨與法案加總:log((P + 0.5) / (N + 0.5))。
- 把法案層級的情緒放進「無異議通過」的 logistic 迴歸。
- 人工驗證:300 段、每段兩個人工評分;以講者群組比較標準化分數;報告的群組層級相關約 0.9——這不是 90% 分類準確率。
- 翻譯本身是測量決策:譯詞的政治用法可能不同、可能有多個對應、詞形與斷詞會影響比對;各語言要分開驗證。相同的類別名稱不保證數值尺度可比。
- 迴歸:814 個法案;三個模型係數都是正的,只有模型 (3) 顯著。這是關聯,不是語氣的因果效果。
補充(非講義內容):+0.5 讓 P 或 N 為 0 時仍可取對數;log ratio 不用 L 當分母,所以「長度加倍、比對也加倍」時分數不變,而 net tone 也不變;但只加長度不加比對時,net tone 會變小,log ratio 不變。試試看。
情緒、立場與衝突
| 概念 | 證據必須建立什麼 |
|---|---|
| Sentiment | 某個定義好的單位中的評價語言 |
| Stance | 對特定目標的支持或反對 |
| Conflict | 行動者或立場之間的實質關係 |
負面字可以描述社會問題,而不是在攻擊另一個政黨。
翻牌卡:三個案例的關鍵數字
LIWC、自訂字典與競選承諾
LIWC 是最常見的「類別百分比」工具;但軟體、官方字典與我們自己的 quanteda 字典是三件不同的事。接著用 Eichorst & Lin(2019)的概念做一個兩句話的「具體 vs 模糊」例子,最後看兩個中文 LIWC 研究。
LIWC:它在量什麼?
- LIWC = Linguistic Inquiry and Word Count:把語言對應到預先定義的字典類別。
- 類別包括代名詞、情緒、社會歷程等;多數類別分數是佔全文字數的百分比。例:100 字中有 4 個類別比對 = 4%。
- 類別百分比量的是用字;詮釋仍需要驗證。
LIWC 與 quanteda:角色分開
| 資源 | 角色 | 取得方式 |
|---|---|---|
| LIWC 應用程式 | 執行內建或自訂字典 | 授權軟體 |
| 官方 LIWC 字典 | 專有的詞—類別資源 | 受授權條款限制 |
| quanteda + 我們的字典 | 在 R 裡用自己的規則比對 | 不需購買 LIWC |
匯入一個檔案,不代表你取得了使用該字典的授權。本週的 teaching_affect.dic 只是借用 LIWC 的檔案格式(% 包住類別編號,下面每行「字 + 類別編號」)。
C16:用 quanteda 套用我們的字典
# C16: Custom dictionary (run C01; stay in W4/classroom)
library(quanteda)
own <- dictionary(file = "Dictionaries/teaching_affect.dic", format = "LIWC")
mini <- tokens(c("Good policy.", "A bad crisis."), remove_punct = TRUE)
matched <- tokens_lookup(mini, own, capkeys = FALSE)
hits <- dfm(matched)
counts <- as.matrix(hits)
counts
word_count <- ntoken(mini)
100 * counts / word_count> library(quanteda)
> own <- dictionary(file = "Dictionaries/teaching_affect.dic", format = "LIWC")
> mini <- tokens(c("Good policy.", "A bad crisis."), remove_punct = TRUE)
> matched <- tokens_lookup(mini, own, capkeys = FALSE)
> hits <- dfm(matched)
> counts <- as.matrix(hits)
> counts
features
docs positive negative
text1 1 0
text2 0 2
> word_count <- ntoken(mini)
> 100 * counts / word_count
features
docs positive negative
text1 50 0.00000
text2 0 66.66667「Good policy.」2 個字中 1 個正面 → 50%;「A bad crisis.」3 個字中 2 個負面 → 66.67%。討論題:為什麼除以全部 token,而不是只除以比對數?(除以比對數只會得到 0 或 100%,失去「用了多少情緒字」的資訊;這也是第 04 章 coverage 與 balance 的差別。)
競選陳述:模糊還是具體?(Eichorst & Lin 2019)
- 問題:政黨什麼時候會做出具體的競選陳述?文本:英文政黨綱領;比較執政地位與經濟表現。
- 字詞密度圖:每欄是一份政黨綱領、每列是一個字典詞;顏色越深=對數次數越大,白色=0。
兩句話的字典例子
老師的 examples/W4_campaign_simple.R,本機執行:
> library(quanteda)
> text <- c("We may improve public services.",
+ "We guarantee better public services.")
> dict <- dictionary(list(vague = "may", concrete = "guarantee"))
> toks <- tokens(text, remove_punct = TRUE)
> counts <- dfm(toks)
> hits <- dfm_lookup(counts, dictionary = dict)
> as.matrix(hits)
features
docs vague concrete
text1 1 0
text2 0 1
> m <- as.matrix(hits)
> 100 * (m[, "concrete"] - m[, "vague"]) / ntoken(toks)
text1 text2
-20 20 - text1:
may比對 vague 一次;text2:guarantee比對 concrete 一次。 - 教學分數 = 100 × (C − V) / L,即「具體百分比 − 模糊百分比」,單位是百分點:text1 = 100 × (0 − 1) / 5 = −20;text2 = +20。
- 改編自 Eichorst & Lin(2019):原論文分母不含停用詞,並把差值重新縮放到 0–1;這個例子兩者都沒做。
第三句對應投影片 73 的「Try: Add not before guarantee」:計數不變(仍是 concrete 1),但 L 變成 7。
中文 LIWC:兩個研究
- Lin(2023):中文的回顧文章,介紹字典類別與用字率,回顧運動傷害、自我效能與運動傳播的研究。討論題:語言能揭露一個隊伍的什麼?
- Lin et al.(2020):類別能區分情緒脈絡嗎?資料:PTT 的 50 篇 Hate 與 50 篇 Sad 貼文;憤怒詞 2.00% vs 0.88%,Cohen’s d = 0.61。群體差異不是個人診斷。
format = "LIWC" 讀一個 .dic 檔,代表?字典之外:POS、TextRank、NER、LLM
這些工具幫我們找候選詞或找名稱,但都不會自動驗證字典。選讀延伸(O01、TextRank、Flair)需要下載模型;本機能跑的照實貼輸出,跑不了的照實說。
POS 標註(UDPipe)
選讀延伸:回到「找候選詞」,現在是 POS → 候選詞 → 人工審查。
# Standalone POS example. No C01 or workflow.R required.
# The model is saved in udpipe_models under your current working directory.
# O01: POS candidates (model download on first run)
# install.packages("udpipe") # run once before class
library(udpipe)
dir.create("udpipe_models", showWarnings = FALSE)
info <- udpipe_download_model("english-ewt",
model_dir = "udpipe_models", overwrite = FALSE)
model <- udpipe_load_model(info$file_model)
text <- "Housing costs are unaffordable."
annotation <- udpipe_annotate(model, x = text, parser = "none")
ann <- as.data.frame(annotation)
ann[, c("token", "lemma", "upos")]
# Optional: retain candidate nouns, adjectives and verbs.
candidates <- subset(ann, upos %in% c("NOUN", "ADJ", "VERB"))
candidates[, c("token", "lemma", "upos")]> library(udpipe)
> dir.create("udpipe_models", showWarnings = FALSE)
> info <- udpipe_download_model("english-ewt",
+ model_dir = "udpipe_models", overwrite = FALSE)
Downloading udpipe model from https://raw.githubusercontent.com/jwijffels/udpipe.models.ud.2.5/master/inst/udpipe-ud-2.5-191206/english-ewt-ud-2.5-191206.udpipe to udpipe_models/english-ewt-ud-2.5-191206.udpipe
- This model has been trained on version 2.5 of data from https://universaldependencies.org
- The model is distributed under the CC-BY-SA-NC license: https://creativecommons.org/licenses/by-nc-sa/4.0
- Visit https://github.com/jwijffels/udpipe.models.ud.2.5 for model license details.
- For a list of all models and their licenses (most models you can download with this package have either a CC-BY-SA or a CC-BY-SA-NC license) read the documentation at ?udpipe_download_model. For building your own models: visit the documentation by typing vignette('udpipe-train', package = 'udpipe')
trying URL 'https://raw.githubusercontent.com/jwijffels/udpipe.models.ud.2.5/master/inst/udpipe-ud-2.5-191206/english-ewt-ud-2.5-191206.udpipe'
Content type 'application/octet-stream' length 16309608 bytes (15.6 MB)
==================================================
downloaded 15.6 MB
Downloading finished, model stored at 'udpipe_models/english-ewt-ud-2.5-191206.udpipe'
> model <- udpipe_load_model(info$file_model)
> text <- "Housing costs are unaffordable."
> annotation <- udpipe_annotate(model, x = text, parser = "none")
> ann <- as.data.frame(annotation)
> ann[, c("token", "lemma", "upos")]
token lemma upos
1 Housing housing ADJ
2 costs cost NOUN
3 are be AUX
4 unaffordable unaffordable ADJ
5 . . PUNCT
> candidates <- subset(ann, upos %in% c("NOUN", "ADJ", "VERB"))
> candidates[, c("token", "lemma", "upos")]
token lemma upos
1 Housing housing ADJ
2 costs cost NOUN
4 unaffordable unaffordable ADJ| 程式 | 做什麼(投影片 78) |
|---|---|
library(udpipe) | 載入已安裝的 R 套件 |
dir.create(...) | 建一個放模型檔的資料夾 |
udpipe_download_model | 下載模型;已有檔案就保留 |
udpipe_load_model | 把模型讀進記憶體 |
udpipe_annotate | 把模型套到我們的句子 |
as.data.frame(annotation) | 把結果轉成表格 |
投影片 79 的輸出:Housing → ADJ、costs → NOUN(lemma cost)、are → AUX、unaffordable → ADJ。token 是觀察到的形式、lemma 是預測的原形、upos 是預測的詞類。本機 O01 輸出與此完全一致。討論:你接受 Housing → ADJ 嗎?
| 方法 | POS 與 token 關係的角色(投影片 80) |
|---|---|
| 候選詞過濾 | 保留名詞或形容詞給人工審查 |
| TextRank | 用 POS 過濾候選;在共現網絡中排名 |
| 依存關係抽取 | 沿著文法連結找字(例如名詞與其修飾語);需要開啟 parser |
TextRank:排名候選詞
資料:quanteda 內建的 Obama 2013 就職演說(examples/W4_keywords_real.R,不需 C01)。節點=候選 lemma;邊=相鄰的名詞/形容詞配對;PageRank 用配對次數與鄰居分數。投影片 82 的實際輸出:new 0.0161、same 0.0096、endure 0.0095、nation 0.0094、common 0.0092、hard 0.0083;並提醒 new 很籠統、有些 endure 被標成名詞。
# Real political speech: Obama 2013 inaugural address. No C01 required.
# Source: https://quanteda.io/reference/data_corpus_inaugural.html
# install.packages(c("quanteda", "udpipe", "textrank", "igraph"))
# The model is saved in udpipe_models under your current working directory.
# O01: POS candidates (model download on first run)
# install.packages("udpipe") # run once before class
library(udpipe)
dir.create("udpipe_models", showWarnings = FALSE)
info <- udpipe_download_model("english-ewt",
model_dir = "udpipe_models", overwrite = FALSE)
model <- udpipe_load_model(info$file_model)
library(quanteda)
library(textrank)
speech <- corpus_subset(data_corpus_inaugural, Year == 2013)
text <- as.character(speech)
ann <- as.data.frame(udpipe_annotate(model, x = text,
parser = "none"))
# Mark candidates, retaining punctuation and other tokens as separators.
keep <- ann$upos %in% c("NOUN", "ADJ")
# This implementation connects immediately adjacent eligible tokens.
# ngram_max controls output phrase length, not the co-occurrence window.
result <- textrank_keywords(ann$lemma, relevant = keep,
ngram_max = 2, sep = " ")
scores <- sort(result$pagerank$vector, decreasing = TRUE)
print(round(head(scores, 6), 4))
# Inspect observed adjacent pairs. cooc is the pair occurrence count.
pairs <- cooccurrence(ann$lemma, relevant = keep)
print(head(pairs, 3))
print(pairs[pairs$term1 == "new" | pairs$term2 == "new", ])
# TextRank (3/3): print the top five and draw their neighbours.
# Scores come from the full TextRank network; we show a smaller part here.
print(round(head(scores, 5), 4))
library(igraph)
top5 <- names(head(scores, 5))
links <- subset(pairs,
term1 %in% top5 | term2 %in% top5)
g <- graph_from_data_frame(links, directed = FALSE)
set.seed(4)
plot(g, layout = layout_with_fr(g),
vertex.size = 6, vertex.color = "#7cae96",
vertex.label.color = "#314f4f",
vertex.label.cex = 1.5,
edge.width = E(g)$cooc)
# Each line is an observed adjacent noun/adjective pair.
# A thicker line means that pair occurs more often.
# Try head(scores, 10), rerun from top5 onwards, and compare the network.
# We do not recompute PageRank on this smaller graph.
# Inspect model predictions before accepting a candidate.
print(ann[ann$lemma == "endure", c("token", "lemma", "upos")])
# Phrase output: freq counts occurrences; it is NOT the PageRank score.
print(head(result$keywords))
# High centrality does not establish relevance or negative evaluation.> library(udpipe)
> dir.create("udpipe_models", showWarnings = FALSE)
> info <- udpipe_download_model("english-ewt",
+ model_dir = "udpipe_models", overwrite = FALSE)
> model <- udpipe_load_model(info$file_model)
> library(quanteda)
Package version: 4.5.1
Unicode version: 17.0
ICU version: 78.3
Parallel computing: 2 of 2 threads used.
See https://quanteda.io for tutorials and examples.
> library(textrank)
> speech <- corpus_subset(data_corpus_inaugural, Year == 2013)
> text <- as.character(speech)
> ann <- as.data.frame(udpipe_annotate(model, x = text,
+ parser = "none"))
> keep <- ann$upos %in% c("NOUN", "ADJ")
> result <- textrank_keywords(ann$lemma, relevant = keep,
+ ngram_max = 2, sep = " ")
> scores <- sort(result$pagerank$vector, decreasing = TRUE)
> print(round(head(scores, 6), 4))
new we require nation common these
0.0125 0.0122 0.0112 0.0090 0.0089 0.0083
> pairs <- cooccurrence(ann$lemma, relevant = keep)
> print(head(pairs, 3))
term1 term2 cooc
1 individual freedom 2
2 new job 2
3 fellow citizen 1
> print(pairs[pairs$term1 == "new" | pairs$term2 == "new", ])
term1 term2 cooc
2 new job 2
30 require new 1
31 new response 1
57 new idea 1
79 new industries 1
> print(round(head(scores, 5), 4))
new we require nation common
0.0125 0.0122 0.0112 0.0090 0.0089
> library(igraph)
Attaching package: ‘igraph’
The following objects are masked from ‘package:stats’:
decompose, spectrum
The following object is masked from ‘package:base’:
union
> top5 <- names(head(scores, 5))
> links <- subset(pairs,
+ term1 %in% top5 | term2 %in% top5)
> g <- graph_from_data_frame(links, directed = FALSE)
> set.seed(4)
> plot(g, layout = layout_with_fr(g),
+ vertex.size = 6, vertex.color = "#7cae96",
+ vertex.label.color = "#314f4f",
+ vertex.label.cex = 1.5,
+ edge.width = E(g)$cooc)
>
> print(ann[ann$lemma == "endure", c("token", "lemma", "upos")])
token lemma upos
872 endures endure VERB
1303 enduring endure VERB
2281 enduring endure VERB
> print(head(result$keywords))
keyword ngram freq
1 we 1 148
2 be 1 57
3 nation 1 8
4 these 1 8
5 citizen 1 7
6 we be 2 6| 名次 | 投影片 82(老師的執行) | 本機(udpipe 0.8.16、textrank 0.3.1、english-ewt 2.5) |
|---|---|---|
| 1 | new 0.0161 | new 0.0125 |
| 2 | same 0.0096 | we 0.0122 |
| 3 | endure 0.0095 | require 0.0112 |
| 4 | nation 0.0094 | nation 0.0090 |
| 5 | common 0.0092 | common 0.0089 |
| 6 | hard 0.0083 | these 0.0083 |
前兩個共現配對(individual–freedom 2、new–job 2)與投影片一致,第三個不同(投影片:other–nation 2;本機:fellow–citizen 1)。本機的 POS 標註看起來有問題:診斷時發現代名詞 we 有 5 次被標成 NOUN、8 次被標成 NUM,因此被當成候選詞;endure 的三個形式都被標成 VERB(投影片說有些被標成名詞)。可能原因(未證實):這台 aarch64 機器上 udpipe 第一次編譯時記憶體不足被中止,改用 -O0 重新編譯;或套件/模型版本與老師不同。同一個模型對 O01 的單句(Housing costs are unaffordable.)結果與投影片 79 完全一致。請以投影片 82–83 的數字為準;本機輸出只用來說明「POS 標註錯誤會直接改變 TextRank 候選」——這正是投影片 82 要你人工審查的理由。
具名實體(Flair,Python 選讀)
POS 標的是詞類;NER 找的是名稱與其類型。投影片 85 的結果:Barack Obama → PER、United Nations → ORG、New York → LOC;United Nations 是一個 entity span。
examples/W4_flair_ner.py 需要 pip install flair(含 PyTorch)並在第一次執行時下載 ner-fast 模型;這台建置機沒有安裝 Flair,因此本教材沒有重跑,以上結果引自投影片 85。
投影片 86:「The minister praised the NHS but criticized its funding.」——提到一個組織,不代表講者支持它;實體提及不是立場。
Embeddings 與 LLM 可以提出候選詞
種子概念 → 建議詞 → 語料中的例子 → 研究者審查。Embeddings 能建議相關說法;LLM 能提出變體或整理候選清單;但也可能冒出反義詞與無關聯想。保留一個獨立的人工基準:這些工具協助開發字典,不能認證效度。
延伸到中文文本
| 選擇 | 例子 |
|---|---|
| 斷詞(Segmentation) | 相關的表達有沒有被切壞? |
| 字形正規化 | 繁簡、異體字是否適當合併? |
| 實體別名 | 縮寫有沒有連到正確的機構? |
| 否定與脈絡 | 這個片語表達支持、批評還是引述? |
要在專案所用的語言與政治場域內驗證。補充(非講義內容):例如「不」「沒有」「未必」在中文常緊貼在評價詞前,斷詞器把「不好」切成一個詞或兩個詞,會直接決定字典能不能比對到「好」。
五句話、三種標記方法
先自己標,再看字典怎麼標:
> library(quanteda)
> dictionary_path <- "Dictionaries/teaching_affect.dic"
> sentences <- c(
+ "This policy is good.",
+ "This policy is bad.",
+ "This policy is not good.",
+ "Excellent, another tax increase.",
+ "The committee met on Tuesday."
+ )
> own_dictionary <- dictionary(file = dictionary_path, format = "LIWC")
> sentence_tokens <- tokens(sentences, remove_punct = TRUE)
> matched_tokens <- tokens_lookup(sentence_tokens, own_dictionary, capkeys = FALSE)
> matched_dfm <- dfm(matched_tokens)
> matched <- as.matrix(matched_dfm)
> net <- matched[, "positive"] - matched[, "negative"]
> total_matches <- rowSums(matched)
> status <- rep("balanced", length(sentences))
> status[net > 0] <- "positive"
> status[net < 0] <- "negative"
> status[total_matches == 0] <- "unmatched"
> dictionary_result <- data.frame(
+ id = seq_along(sentences), sentence = sentences,
+ positive = matched[, "positive"], negative = matched[, "negative"],
+ dictionary_status = status, row.names = NULL
+ )
> print(dictionary_result, row.names = FALSE)
id sentence positive negative dictionary_status
1 This policy is good. 1 0 positive
2 This policy is bad. 0 1 negative
3 This policy is not good. 1 0 positive
4 Excellent, another tax increase. 1 0 positive
5 The committee met on Tuesday. 0 0 unmatched
> assumed_latency <- data.frame(
+ method = c("Dictionary", "Transformer classifier", "Prompted LLM"),
+ sentences_per_batch = 5L,
+ assumed_seconds = c(0.02, 0.30, 3.00)
+ )
> cat("\nFICTIONAL batch times, not measurements. No Transformer or LLM was run.\n")
FICTIONAL batch times, not measurements. No Transformer or LLM was run.
> print(assumed_latency, row.names = FALSE)
method sentences_per_batch assumed_seconds
Dictionary 5 0.02
Transformer classifier 5 0.30
Prompted LLM 5 3.00
> cat("\nCheck negation and possible irony; unmatched does not establish neutral sentiment.\n")
Check negation and possible irony; unmatched does not establish neutral sentiment.投影片 90 的時間比較是假設性的(字典 0.02 秒、transformer 0.30 秒、LLM 3.00 秒),老師的腳本也明說「FICTIONAL batch times, not measurements. No Transformer or LLM was run.」更快的標記能回答研究問題嗎?還需要哪些驗證?
回到專題+課後 Lab 四個任務
投影片最後一段把全部概念收回到「寫 methods section」與「你自己的專題」。接著是課後 Lab(45–60 分鐘、不計分、不必繳交)的四個任務;以下輸出都是本機執行 W4/lab/Lab_Session_W4.R 與 answers/Lab_Session_W4_Answers.R 的結果。
Methods section 應該報告什麼
- 語料範圍、來源與分析單位。
- 字典來源、版本、語言與修改。
- 比對、前處理、分母與零的規則。
- 人工驗證的設計、結果與剩下的錯誤。
- 足以稽核整個流程的程式碼與取得資訊。
把概念套到研究專題
投影片 92 的句型:我想量 …,而不只是數 …;我的分析單位是 …;一個可能的 false positive 是 …;一個可能的 false negative 是 …;我會用 … 驗證這個測量。開場問題的延伸:還需要哪些規則才能辨識對家戶狀況的負面評價?投影片 93:字典適合你的專案嗎?列兩個優點、兩個限制;速度、透明度與脈絡敏感度怎麼取捨?
第 14 章有一個研究計畫填寫器,把這些句型整理成 Markdown。
O02:你自己的政策字典(選做挑戰)
加入一個有理由的能源政策詞,然後兩人一組:找一段支持它的段落、一段可能的 false positive。
my_dict <- dictionary(list(energy = c("energy", "gas bills")))
matched <- tokens_lookup(discovery_tokens, my_dict)
my_dfm <- dfm(matched)
my_counts <- as.numeric(my_dfm[, "energy"])
sum(my_counts > 0)
my_context <- kwic(discovery_tokens, "energy", window = 6)
head(my_context, 3)第 02 章的 KWIC 判讀練習與第 07 章的字典驗證台可以當作 O02 的線上版。
Lab 任務 1:讀字典、看比對
Setup 區塊(和 C01 相同,會 source("workflow.R"))跑完後,先讀 .dic 原始檔:
> readLines("Dictionaries/teaching_affect.dic")
[1] "%" "1 positive" "2 negative" "%" "good 1" "excellent 1" "success 1"
[8] "successful 1" "improve 1" "bad 2" "failure 2" "crisis 2" "harm 2" "harmful 2"
> toy_sentiment <- dictionary(file = "Dictionaries/teaching_affect.dic",
+ format = "LIWC")
> toy_sentiment
Dictionary object with 2 key entries.
- [positive]:
- excellent, good, improve, success, successful
- [negative]:
- bad, crisis, failure, harm, harmful> texts <- c("The policy is good.", "The policy is not good.")
> example_tokens <- tokens(texts, remove_punct = TRUE)
> example_dfm <- dfm(example_tokens)
> example_hits <- dfm_lookup(example_dfm, toy_sentiment)
> counts <- convert(example_hits, to = "data.frame")
> counts
doc_id positive negative
1 text1 1 0
2 text2 1 0> word_count <- ntoken(example_tokens) > positive <- counts$positive > negative <- counts$negative > net_score <- 100 * (positive - negative) / word_count > net_score text1 text2 25 20
25 和 20:一個正面比對除以 4 字與 5 字。第二句分數較低是因為 not 增加了分母,不是因為規則認出了否定。
> # The setup above created these five named examples.
> check_texts
good negated unmatched
"The policy is good." "The policy is not good." "The minister spoke today."
balanced empty
"A good plan with a bad outcome." ""
> check_tokens <- tokens(check_texts, remove_punct = TRUE)
> check_dfm <- dfm(check_tokens)
> check_hits <- dfm_lookup(check_dfm, toy_sentiment)
> convert(check_hits, to = "data.frame")
doc_id positive negative
1 good 1 0
2 negated 1 0
3 unmatched 0 0
4 balanced 1 1
5 empty 0 0
> # Prepared by workflow.R using the three formulas in the table above.
> check_scores
doc_id tokens positive negative net_per100 coverage_per100 balance no_match
1 good 4 1 0 25 25.00000 1 FALSE
2 negated 5 1 0 20 20.00000 1 FALSE
3 unmatched 4 0 0 0 0.00000 NA TRUE
4 balanced 7 1 1 0 28.57143 0 FALSE
5 empty 0 0 0 NA NA NA TRUELab 任務 2:改一條能源政策規則
- 1 — 相關:討論能源生產、供應、價格、負擔能力或轉型(如電費、暖氣費、再生能源、煤礦關閉)。有一段實質討論就夠,講者不必支持政策。
- 0 — 不相關:政治上的
power、無關的立法bill、個人的energy、催淚gas都不算。一般氣候討論只有連到能源時才算。 - 不確定:留空、寫下原因、計分前討論。不要把不確定當成 0。
> policy_entries <- read.csv("Dictionaries/energy_policy.csv")
> head(policy_entries)
version category pattern
1 v1 energy energy
2 v1 energy power
3 v1 energy electric*
4 v1 energy gas
5 v1 energy bill*
6 v2 energy energy
> # Read the v1 patterns, then put them in a dictionary category.
> v1_entries <- subset(policy_entries, version == "v1")
> energy_v1 <- dictionary(list(energy = v1_entries$pattern))
> v2_entries <- subset(policy_entries, version == "v2")
> energy_v2 <- dictionary(list(energy = v2_entries$pattern))
> energy_v1
Dictionary object with 1 key entry.
- [energy]:
- energy, power, electric*, gas, bill*
> energy_v2
Dictionary object with 1 key entry.
- [energy]:
- energy, electric*, gas bill*, renewab*, solar*, wind farm*, fossil fuel*
> contexts <- kwic(discovery_tokens, pattern = c("power", "gas", "bill*"),
+ valuetype = "glob", window = 8)
> head(contexts, 10)
Keyword-in-context with 10 matches.
[speech_0006, 32] opinion. on the question whether any additional | power |
[speech_0006, 37] whether any additional power is given by the | bill |
[speech_0006, 233] the case. the third object of the | bill |
[speech_0006, 254] acquired for public purposes. in effect the | bill |
[speech_0008, 24] special act undertakers will be over-ridden by this | bill |
[speech_0019, 38] were very widely published and there was a | power |
[speech_0019, 165] considered these proposals very carefully. he had | power |
[speech_0021, 36] it would facilitate the further progress of the | bill |
[speech_0021, 61] to avoid lengthening the committee stage. this | bill |
[speech_0021, 426] to remove them. there are in the | bill |
is given by the bill to local authorities
to local authorities in blighted areas—not war-damaged areas—i
is to regulate the compensation payable in respect
provides that where land is compulsorily acquired for
, particularly as regards special provisions which may
, which we can be quite certain was
under the act to submit them to the
if we were to have a reply to
is a very drastic measure. the housing
at present no default powers. if a > first_id <- contexts$docname[1] > original <- subset(speeches, doc_id == first_id) > original$text [1] "I will try again, but I repudiate the idea that I had any irritation at all: that is a matter of opinion. On the question whether any additional power is given by the Bill to local authorities in blighted areas—not war-damaged areas—I say the answer is, \"Yes.\" To start with, it affords greater expedition in acquisition. It absolves them from personal notifications and allows them to give bl …〔以下略〕
> energy_revised <- dictionary(list(
+ energy = c("energy", "wind farm*", "electric*", "gas", "bill*")
+ ))
> revision_texts <- c(
+ wind = "The government should approve new wind farms.",
+ authority = "Parliament must retain the power to question ministers."
+ )
> revision_tokens <- tokens(revision_texts, remove_punct = FALSE)
> before_tokens <- tokens_lookup(revision_tokens, energy_v1, capkeys = FALSE)
> before_counts <- convert(dfm(before_tokens), to = "data.frame")
> after_tokens <- tokens_lookup(revision_tokens, energy_revised, capkeys = FALSE)
> after_counts <- convert(dfm(after_tokens), to = "data.frame")
> data.frame(sentence = before_counts$doc_id,
+ before = before_counts$energy,
+ after = after_counts$energy)
sentence before after
1 wind 0 1
2 authority 1 0answers 的解讀:wind 從 0 變 1,authority 從 1 變 0——這個修改修好了兩個例子。接著要檢查其他句子還剩哪些錯。
> matched_tokens <- tokens_lookup(discovery_tokens, energy_v2, capkeys = FALSE)
> match_dfm <- dfm(matched_tokens)
> head(match_dfm, 6)
dfm of 6 documents x 1 feature (0 occurrences, 100.00% sparsity) and 12 docvars.
features
docs energy
speech_0001 0
speech_0002 0
speech_0003 0
speech_0004 0
speech_0005 0
speech_0006 0Lab 任務 3:檢查開發集錯誤
> # Read the labelled teaching examples and generate predictions explicitly.
> synthetic <- read.csv("Data/synthetic_validation.csv")
> example_corpus <- corpus(synthetic, text_field = "text", docid_field = "doc_id")
> example_tokens <- tokens(example_corpus, remove_punct = FALSE)
> # Apply v1, then v2. Each matched phrase counts once.
> v1_matches <- tokens_lookup(example_tokens, energy_v1, capkeys = FALSE)
> v1_dfm <- dfm(v1_matches)
> v1_binary <- dfm_weight(v1_dfm, scheme = "boolean")
> v1_predictions <- convert(v1_binary, to = "data.frame")
> synthetic$v1 <- v1_predictions$energy
> v2_matches <- tokens_lookup(example_tokens, energy_v2, capkeys = FALSE)
> v2_dfm <- dfm(v2_matches)
> v2_binary <- dfm_weight(v2_dfm, scheme = "boolean")
> v2_predictions <- convert(v2_binary, to = "data.frame")
> synthetic$v2 <- v2_predictions$energy> dev <- subset(synthetic, split == "development")
> dev[, c("doc_id", "text", "human", "v1", "v2")]
doc_id text human v1 v2
1 dev01 We must address rising energy prices. 1 1 1
2 dev02 Electricity supply needs public investment. 1 1 1
3 dev03 Families cannot afford their gas bills. 1 1 1
4 dev04 Subsidies should support solar panels. 1 0 1
5 dev05 The government should approve new wind farms. 1 0 1
6 dev06 We should reduce fossil fuel imports. 1 0 1
7 dev07 Parliament must retain the power to question ministers. 0 1 0
8 dev08 This bill reforms criminal sentencing. 0 1 0
9 dev09 Police used tear gas at the protest. 0 1 0
10 dev10 The minister brought energy to the debate. 0 1 1
11 dev11 Schools need a larger budget. 0 0 0
12 dev12 The committee discussed train timetables. 0 0 0worked answers 只列出 v1 判錯的開發句:
> errors <- subset(dev, v1 != human)
> errors[, c("doc_id", "text", "human", "v1", "v2")]
doc_id text human v1 v2
4 dev04 Subsidies should support solar panels. 1 0 1
5 dev05 The government should approve new wind farms. 1 0 1
6 dev06 We should reduce fossil fuel imports. 1 0 1
7 dev07 Parliament must retain the power to question ministers. 0 1 0
8 dev08 This bill reforms criminal sentencing. 0 1 0
9 dev09 Police used tear gas at the protest. 0 1 0
10 dev10 The minister brought energy to the debate. 0 1 1answers 的說明:開發句顯示為什麼可能要拿掉單獨的 power、gas、bill*,並加入再生能源、太陽能板、風場與化石燃料的說法。第 07 章的「字典驗證台」可以直接互動做這一步。
Lab 任務 4:固定 v2,在測試句上算 precision/recall/F1
> test <- subset(synthetic, split == "test")
> # 0 = not relevant; 1 = relevant. Keep both categories in the table.
> predicted <- factor(test$v2, levels = c(0, 1))
> human <- factor(test$human, levels = c(0, 1))
> table(predicted, human)
human
predicted 0 1
0 5 2
1 1 4> # Compare each dictionary prediction with its teaching label. > TP <- sum(test$v2 == 1 & test$human == 1) > FP <- sum(test$v2 == 1 & test$human == 0) > FN <- sum(test$v2 == 0 & test$human == 1) > TN <- sum(test$v2 == 0 & test$human == 0) > precision <- TP / (TP + FP) > recall <- TP / (TP + FN) > F1 <- 2 * TP / (2 * TP + FP + FN) > c(TP = TP, FP = FP, FN = FN, TN = TN) TP FP FN TN 4 1 2 5 > c(precision = precision, recall = recall, F1 = F1) precision recall F1 0.8000000 0.6666667 0.7272727
> errors <- subset(test, v2 != human)
> errors[, c("doc_id", "text", "human", "v2")]
doc_id text human v2
17 test05 The closure of coal mines requires a transition plan. 1 0
18 test06 Heating tariffs must remain affordable. 1 0
22 test10 Her energy transformed the committee. 0 1- v2:TP = 4、FP = 1、FN = 2、TN = 5;precision 0.80、recall 0.667、F1 0.727,與投影片 95 一致。
- answers:v1 找到同樣 4 句相關句,但也標了 4 句不相關句。
- 如果現在加
coal或heating,就是用測試句的資訊改字典;要評估新版本,需要一組新的測試集。 - 這些結果只描述 12 句測試句;要評估國會發言,需要那些發言的人工標記。
W6 預習:五篇文本、一個困難決定
W5(10 月 9 日)放假;W6(10 月 16 日)談人工編碼與分類。現在先用簡短 codebook 標五篇、說明一個不確定的決定、把字典預測分開保存;約 10 分鐘,不用訓練模型也不用上傳。
> development_texts <- subset(coding_template, split == "development")
> preview <- head(development_texts, 5)
> preview[, c("doc_id", "text")]
doc_id
1 speech_3484
2 speech_0299
3 speech_3560
4 speech_1238
5 speech_0963
…〔以下略〕
1 That is why I have appealed to the Disraeli wing of the Conservative party, which formed a radical, reforming Government who addressed some of the abuses of power of previous Governments. In appealing to Conservative Members to support the amendments, I draw their attention to the congruity between the intent and content of the amendments and the policies set out in their party's manifesto at th …〔以下略〕
2 …〔以下略〕
3 This petition is signed by more …〔以下略〕
4 …〔以下略〕
5 …〔以下略〕選做:政黨比較
> # quanteda adds counts within each party.
> party_matches <- tokens_lookup(policy_tokens, energy_v2, capkeys = FALSE)
> party_dfm <- dfm(party_matches)
> party_dfm <- dfm_group(party_dfm, groups = party)
> # Group original word counts separately to preserve the denominator.
> party_words <- dfm(toks)
> party_words <- dfm_group(party_words, groups = party)
> party_summary <- convert(party_dfm, to = "data.frame")
> party_summary$tokens <- ntoken(party_words)
> party_summary$per1000 <- 1000 * party_summary$energy / party_summary$tokens
> head(party_summary, 6)
doc_id energy tokens per1000
1 Alliance Party of Northern Ireland 0 44 0.00000000
2 Communist Party of Great Britain 0 36 0.00000000
3 Conservative 151 447158 0.33768824
4 Democratic Unionist Party 1 11814 0.08464534
5 Green Party of England and Wales 2 217 9.21658986
6 Independent 1 1394 0.71736011注意 Lab 版本用 dfm_group() 加總,結果應與第 06 章 party_rates 的 v2 一致(同樣是先加總再相除)。
執行清單
文獻導讀
指定閱讀三篇(投影片 98)。這三篇的全文都不在課程 repo 內,所以下面的卡片只整理投影片的陳述(附投影片頁碼),不引用論文頁碼。repo 裡唯一相關的合法全文是 W1 的 Grimmer & Stewart(2013),它的字典段落附論文頁碼。
Denny & Spirling (2018)
Rauh (2018)
Proksch, Lowe, Wäckerle & Soroka (2019)
Grimmer & Stewart (2013)(repo:W1/papers/Grimmer2013.pdf)
延伸閱讀與軟體(投影片 99)
- Grimmer, Roberts & Stewart (2022). Text as Data. Chapters 5 and 16.
- Hvitfeldt & Silge. Supervised Machine Learning for Text Analysis in R. tokenization 與 stopwords 章節(線上)。
- Eichorst & Lin (2019). “Resist to Commit.” The Journal of Politics 81(1): 15–32.
- Boyle et al. (2025). “Catalysts for progress? Mapping policy insights from energy research.” Energy Research & Social Science 121: 103955.
- 軟體:quanteda(字典、KWIC、比對)、quanteda.textstats(頻率、搭配詞、keyness)、UDPipe/TextRank、ggplot2、Flair(Python NER)、irr(編碼者一致性)、LIWC。
以上延伸閱讀的全文同樣不在 repo;如需細讀,可透過台大圖書館或學校 VPN 取得全文。
常見陷阱與詞彙表
十個常見陷阱
把「提到」當成「評價」
提到 inflation 不代表負面評價家戶狀況(投影片 3)。議題詞量注意力,評價詞量情緒,兩者要連到同一個對象。
把情緒當立場
負面語言描述問題,同時可能支持某政策(投影片 4、66)。
只比次數、不除長度
speech_2792 有 20 次 bill* 比對但每百字 1.48;speech_4435 只有 4 次卻是 5.80(投影片 31)。
把 0 當中性
沒比對到與正負相抵都是 0;空文本是 NA(投影片 34)。
先刪停用詞再比對否定或片語
not 在 stopwords("en") 裡會被刪掉(投影片 36);片語要在刪停用詞之前比對(投影片 29)。
萬用字元太寬
bill* 抓到 billion、billericay(投影片 28)。
只讀比對到的段落就宣稱 recall
沒有比對到的段落才找得到 false negatives(投影片 50)。
在測試集上繼續調字典
凍結後才測試;用了測試資訊就需要新的測試集(投影片 24、95;Lab answers)。
把群組相關當分類準確率
Proksch et al. 的 0.9 是群組層級相關(投影片 63)。
以為有現成字典就合適/有授權
Availability is not evidence of suitability(投影片 14);匯入檔案不等於取得授權(投影片 68)。
翻牌卡:公式與定義
詞彙表
總複習、研究計畫與參考文獻
我的進度
總複習(20 題)
研究計畫填寫器
參考文獻(依投影片 98–99 與各頁引用)
- Boyle et al. (2025). “Catalysts for progress? Mapping policy insights from energy research.” Energy Research & Social Science 121: 103955.
- Denny, M. J., and A. Spirling (2018). Political Analysis 26(2): 168–189.
- Eichorst, J., and N. C. N. Lin (2019). “Resist to Commit.” The Journal of Politics 81(1): 15–32.
- Grimmer, J., M. E. Roberts, and B. M. Stewart (2022). Text as Data. Princeton University Press. Chapters 5 and 16.
- Grimmer, J., and B. M. Stewart (2013). “Text as Data.” Political Analysis 21(3): 267–297.
- Hvitfeldt, E., and J. Silge (2022). Supervised Machine Learning for Text Analysis in R.
- Lin, W.-F. (2023). “Linguistic inquiry and word count in sport and exercise.” Physical Education Journal 56(1): 1–16. doi:10.6222/pej.202303_56(1).0001(投影片 75)
- Lin, W.-F., C.-L. Huang, Y.-C. Lin, C.-L. Lee, and J. W. Pennebaker (2020). “The Revision of the Chinese Linguistic Inquiry and Word Count Dictionary 2015.” Survey Research – Method and Application 45: 73–118. doi:10.7014/SRMA.2020100004(投影片 76)
- Proksch, S.-O., W. Lowe, J. Wäckerle, and S. Soroka (2019). Legislative Studies Quarterly 44(1): 97–131.
- Rauh, C. (2018). Journal of Information Technology & Politics 15(4): 319–343.