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

W4:字典與情緒分析(Dictionaries and Sentiment Analysis)

W2 把文字切成 token、做成 DFM;W4 往前一步:先定義要量的概念,再用一份「詞 → 類別」的對照表(dictionary)把文字變成分數,最後拿人工判斷來驗證這個分數到底量到了什麼。

本週學習目標 投影片 2

投影片 2 列了五個目標,前四個對應本教材的四大區塊,第五個接到你自己的期末專題。讀完後回來勾選:

  1. Measurement:說清楚一個字典分數「打算量什麼」。(第 00、04 章)
  2. Dictionary construction:用政治文本建立並修訂詞表或片語表。(第 02、03、06 章)
  3. Scoring:把比對結果變成分數,並解釋分母與「沒有任何比對」的文本。(第 04、05 章)
  4. Validation:用已發表的證據與人工判斷評估效度。(第 07、08 章)
  5. Own project:為自己的研究規劃一個字典測量。(第 11、14 章的計畫填寫器)

一個政治學研究問題 投影片 3

本週的引導問題:國會議員什麼時候會用負面的方式描述家戶經濟狀況?例句是「Families cannot afford rent or energy bills.」可以比較的對象包括講者、時期或執政/在野。

關鍵是同時讀兩件事:rent 告訴我們議題(家戶開銷),cannot afford 才是評價(困難)。投影片的提醒:提到 inflation 並不代表議員怎麼評價家戶狀況。投影片 3

注意力、情緒、立場:三個不同的問題 投影片 4

概念問的是投影片例句
Issue attention(議題注意力)提到了什麼?This speech discusses energy bills.
Sentiment(情緒)某件事被怎麼評價?High energy bills are hurting families.
Stance(立場)對某個目標採取什麼立場?I support the government’s price cap.
投影片 4 的重點

描述問題時用的負面字,可能同時伴隨支持某項政策。「負面情緒」不等於「反對」。

一條測量流程 投影片 5

點下面每一步看說明(內容取自投影片 5):

1
找相關句子
→
2
編碼評價與對象
→
3
對照人工判斷
→
4
比較講者或時期
  1. 找相關句子:家戶所得、生活開銷、負擔能力。
  2. 編碼評價與其對象:家戶狀況被怎麼描述?
  3. 對照人工判斷驗證:同時納入字典有比對到與沒比對到的文本。
  4. 比較講者或時期:被判為負面的相關句子 ÷ 所有相關句子。

投影片 5 也坦白說:今天的課分開練習兩件事——計算議題提及與計算正負面字;要真正回答開場問題,還得把「評價」連到它的「對象」,這一步今天沒有完成。投影片 5

概念、指標、分數、主張 投影片 6

層次具體例子(投影片 6)
Construct(概念)議員談家戶開銷有多少
Indicator(指標)計算 rent、energy bills(一個片語比對)等詞的比對次數
Score(分數)演說 A:4 次 / 100 字 = 每百字 4;演說 B:4 / 200 = 每百字 2
Claim(主張)每 100 字中,A 的家戶開銷比對次數是 B 的兩倍
🧮小計算:同樣 4 次比對,分母不同投影片 6 的數字
預設值重現投影片 6:A = 4 per 100,B = 2 per 100。

注意投影片 6 最後一句:這只是在數提及;要量負面評價,還要辨識 cannot afford 這類語言。

同一份語料,不同的分析單位 投影片 7

文本單位對應的政治學問題
Sentence(句子)哪些陳述在講家戶困難?
Speech(一次發言)一次發言有多少比例在談困難?
Speaker-period(講者 × 時期)某位講者的注意力如何隨時間改變?

本週練習資料:5,000 筆英國下議院(House of Commons)發言,1945–2025(Data/hc_sample_1945_2025.rds)。切分或合併文本時,要保留講者、日期與來源 ID。投影片 7

練習:這句話在量哪一種概念?

每句選一個:議題注意力、情緒、立場。(例句改寫自投影片 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/ 匯出)、玩具直覺(標「補充(非講義內容)」)、練習(作答區、翻牌卡、主張判斷、計畫填寫器)。
  • 進度、作答只存在這台瀏覽器;側欄可看完成度。
章末測驗:「High energy bills are hurting families.」主要對應哪一個概念?
投影片 4 把這句當作 sentiment 的例子:它評價了 energy bills 的影響,但沒有表態支持或反對某個政策。投影片 4
演說 A 有 4 次比對、100 字;演說 B 有 4 次比對、200 字。哪個說法正確?
分數取決於分母。投影片 6 的主張是「每 100 字」的比較。投影片 6
01 · 先建立直覺

Bag of words、DFM 與字典

字典方法建立在 W2 的 bag-of-words 之上:文件被拆成 token、數成一張文件 × 特徵的表(DFM)。這一章先跑 C01 載入資料,再用兩句話的小例子看清楚 DFM、文件長度與字典比對。

C01:一次設定,整堂課共用 投影片 8

每份文件是一次國會發言(speech contribution)。C01 會找到 workflow.R、切換工作目錄並 source() 它;workflow.R 一口氣準備好後面要用的物件:speeches、discovery_tokens、comparison、check_scores、policy_scores、validation 等。之後保持同一個 R session。

R · C01(W4/classroom/W4_classroom.R)
# 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")
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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")
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:計數與文件長度 投影片 9–10

先預測:A 這列的 prices 會是幾?

R · C02(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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 次。投影片 10
  • 長度不一樣:A 有 5 個 token,但表上只顯示 3 次——worry 和 voters 沒被選進來。這就是後面「分母要用全部 token」的伏筆。
  • dfm() 預設轉小寫,所以 Prices 與 prices 是同一欄。

互動:自己做一張 DFM

🧱迷你 tokens → DFM玩具直覺型 · 預設值=投影片 9 的 C02 例子

補充(非講義內容):這裡的切字規則是簡化版(以空白與標點切開),對英文短句與 quanteda 結果一致,但不處理連字號、縮寫等細節。

字數表丟掉了什麼 投影片 11

The government does not support the opposition.

The opposition does not support the government.

同一袋字,誰對誰完全相反。這也是為什麼 W4 之後要談片語(第 03 章)、否定(第 05 章)與「情緒 ≠ 立場」(第 08 章)。在上面的互動元件把兩句貼進 A、B、清空特徵欄,就會看到兩列完全相同。

什麼是字典? 投影片 12

字典把「表達方式」對應到事先定義好的類別。quanteda 的寫法:

R · 投影片 12
library(quanteda)
dic <- dictionary(list(
  household_costs = c("inflation", "rent", "energy bills"),
  employment = c("unemployment", "job security")
))

投影片 12:提到家戶開銷,不代表就證明了經濟困難。

套用我們的字典 投影片 13

老師把投影片 12–13 合成一個可獨立執行的檔案 examples/W4_dictionary_simple.R。本機執行結果:

R console output(本機實跑 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          1

rent + energy bills 給 2 次比對;job security 給 1 次。注意 energy bills 是片語:tokens_lookup() 會在 token 序列上找連續兩個字,算一次。與投影片 13 的表一致。投影片 13

C02 中 A 列顯示的計數加總是 3,但 ntoken() 是 5。原因?
投影片 10:Length is different… worry and voters are not shown。投影片 10
「Rent and energy bills are rising.」用投影片 12 的字典,household_costs 計幾次?
片語整體算一次比對。投影片 13
02 · 建字典

找候選詞:頻率、KWIC、搭配詞、keyness

字典可以沿用、改編或自建,但「現成的」不等於「合適的」。這一章跑 C03–C06,用四種工具從 4,950 篇 discovery 發言裡找候選詞,並且每一步都回去讀上下文。

沿用、改編,還是自建? 投影片 14

選擇主要問題
現成字典(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 章導讀)。

建立或改編詞表的四步 投影片 15

  1. 寫下什麼該算,並附一個不該算的例子。
  2. 閱讀有談與沒談該議題的段落。
  3. 列出代表該議題的字與片語。
  4. 檢查誤比對(false matches)與詞表漏掉的相關段落。

以家戶開銷為例:要分辨 energy bills(帳單)和國會的 bill(法案)。投影片 15

C03:頻率——出現次數 vs 出現在幾篇 投影片 16–17

R · C03(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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   all
  • frequency:總出現次數;docfreq:有出現的發言篇數;rank 依 frequency 排序;group = all 表示全部發言合併計算。投影片 17
  • 本機結果與投影片 17 完全一致:hon 6,514 次、出現在 2,826 篇。
  • 練習:把 6 改成 12,哪些字是在描述議事程序而不是政策?(hon、right、member 是「the right hon. Member」這種稱呼。)
📊頻率表瀏覽器真實資料 · recap_dfm 前 60 名
點一個字把它標成「程序用語」(再點一次取消):

C04:KWIC——把字放回上下文 投影片 18–19

KWIC = keyword in context。security 一定指國防嗎?

R · C04(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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——同一個字,兩種意思。投影片 19

🔎KWIC 判讀練習真實資料 · discovery_tokens,window = 8

把每一列標成「相關」或「誤比對」,下面會統計你的判讀。這裡的「相關」請你自己定義(例如 security=國防/安全政策)。

資料說明:本機用 kwic(discovery_tokens, pattern, window = 8) 匯出;比對超過 150 次的字隨機抽 150 列(set.seed(4))。

C05:搭配詞——候選片語 投影片 20–21

Collocation:相鄰且統計上強烈相關的兩個字。依 lambda 由大到小排序。

R · C05(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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。投影片 21
  • 強搭配詞只是候選:地名本身不能量家戶開銷。
🔗搭配詞表:min_count 20 vs 50真實資料
投影片 20 的練習:把 min_count 提到 50,前面的片語是在談家戶開銷嗎?(count ≥ 50 的表是從同一次 min_count = 20 的結果再篩選 count ≥ 50;λ 由同一次估計得到。)

C06:Keyness——比較兩群 投影片 22–23

R · C06(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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
Wordchi2Con.Lab.Wordchi2Con.Lab.
aircraft44.3711631waste61.4331124
cyberstalking39.62420tory49.501173
stalking33.96360advertising38.721264
  • 兩個 target 各跑一次,每個表顯示該黨前三個正 keyness 分數。
  • keyness 考慮了每群的 token 總數——光看次數不能決定。
  • 這些字是這份樣本中的特徵詞,不一定最常見,也跟情緒正負無關。投影片 23
⚖️Keyness 前 15 名真實資料 · chi2
長條=chi2;括號內為 target/reference 的次數。補充(非講義內容):cyberstalking、stalking 在 Labour 是 0 次——可能只是某幾篇 Conservative 發言集中談同一議題,樣本特徵不等於政黨特徵。

把「找詞」和「評估」分開 投影片 24

A
Discovery texts
→
B
候選詞 → 人工審查
→
C
凍結字典
→
D
Held-out texts+獨立人工標記
→
E
錯誤分析
  • 記錄字典版本與納入規則。
  • 不要在最終評估樣本上繼續調整。
  • 語言或時期改變時要重新檢查表現。投影片 24

對應到程式:workflow.R 把 50 篇 test 發言從 discovery_tokens 拿掉,所以 C03–C06 找詞時根本看不到它們。

C03 中 hon 的 frequency = 6,514、docfreq = 2,826。docfreq 的意思是?
frequency counts occurrences; docfreq counts speeches with a match。投影片 16–17
C05 依 lambda 排第一的搭配詞是 sri lanka。這代表?
兩次比對都來自同一篇發言;地名本身不量家戶開銷。投影片 21
為什麼要把 50 篇 test 發言排除在 discovery 之外?
Do not keep tuning on the final evaluation sample。投影片 24
03 · 比對規則

比對規則:片語與萬用字元

同一個概念可以寫成很多種規則:寬的 bill*、精確的 bill/bills、片語 energy bills。規則越寬,誤比對越多;規則越窄,漏掉越多。

一個可以手算的小例子 投影片 25

文本寬規則 bill*片語 energy bills
Energy bills are rising.11
This bill reforms parliament.10
Families cannot afford heating.00

改用片語去掉了一個 false positive(法案),但仍然漏掉一個相關段落(買不起暖氣)。投影片 25

C07:用 quanteda 比對片語 投影片 26

R · C07(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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 精確比對 投影片 27–28

R · C08(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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â)。這些是比對次數,不是篇數。投影片 28
✱bill* 抓到了哪些字?真實資料 · table(wild$keyword)

互動:規則測試台

🧪寫一條規則,看三句話怎麼被比對玩具直覺型 · 預設=投影片 25–26

補充(非講義內容):比對邏輯模仿 tokens_lookup() 的 glob 規則(不分大小寫、* 代表任意字尾、片語須連續出現、保留標點時片語不能跨過句號)。

片語規則保留有用的脈絡 投影片 29

  • 片語能分出能源帳單與立法法案。
  • 越長的 n-gram 帶有越多在地脈絡。
  • 但越具體的表達也越罕見。
  • 先比對片語,再移除停用詞——不然 cannot afford 之類的片語可能先被拆壞。

投影片 29 的圖(Hvitfeldt & Silge 2022):每個點是一篇 Andersen 童話在某個 n-gram 長度下的不同 n-gram 數;n 越大,最常見的 n-gram 次數越少(顏色越紫)。

C08 的萬用字元有 1,774 次比對、精確有 1,539 次。差額主要來自?
bill* matches any suffix after bill, including billion。投影片 28
改用精確比對 bill/bills 能解決什麼?
Exact matching still mixes legislation and household bills。投影片 28
04 · 計分

分母、情緒分數與「零」

比對完之後要變成數字。這一章談三件事:除以什麼(C09)、兩種情緒摘要(net tone 與 coverage)、以及零分不一定是中性(C10)。

C09:文件長度與分母 投影片 30–31

預測:用「次數」與用「比率」排出來的前幾名會一樣嗎?

R · C09(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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
  • 本機輸出的六列與投影片 31 完全相同。
📏次數排名 vs 比率排名真實資料 · 4,950 篇 discovery 發言的 bill* 比對
依次數排序(前 5)
依每百字比率排序(前 5)

兩種簡單的情緒摘要 投影片 32

令 P = 正面比對數、N = 負面比對數、L = 原始 token 數。

摘要定義解讀
Net tone100 × (P − N) / L每 100 個 token 的淨比對數
Match coverage100 × (P + N) / L每 100 個 token 中被比對到的情緒 token

P = 3、N = 1、L = 100:net tone = 2,coverage = 4%。投影片也預告:後面 Proksch et al. 的案例用的是另一種計分規則(第 08 章)。投影片 32

C10:零不一定是中性 投影片 33–34

check_texts 是 workflow.R 建的五個教學例子;情緒字典是十個字的 Dictionaries/teaching_affect.dic(positive:good、excellent、success、successful、improve;negative:bad、failure、crisis、harm、harmful)。

R · C10(W4/classroom/W4_classroom.R)
# C10: Zero, balance and missing matches
check_texts
check_scores[, c("doc_id", "positive", "negative",
                 "net_per100", "coverage_per100", "balance")]
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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)
good1 個正面比對 / 4 字 → 每百字 25;所有比對都是正面,balance = 1。
negated1 個正面比對 / 5 字 → 20。規則忽略了 not。
unmatched有文字但 P = N = 0;balance 的分母是 0 → NA。
balancedP = N = 1、共 7 字:net = 0,coverage = 100 × 2 / 7 = 28.57%。
emptyL = 0 且 P + N = 0:三個分數都無定義(NA)。
投影片 34 的結論

零可以代表「沒比對到」也可以代表「正負相抵」;兩者都不能證明中性。

🎚情緒計分器(teaching_affect.dic)玩具直覺型 · 預設五句=check_texts

未勾選時,計算方式與 workflow.R 的 score_sentiment() 相同(去標點、轉小寫、分母為全部 token;分母為 0 時給 NA)。最後一行空白對應 empty。勾選的否定規則是補充(非講義內容),用來對照第 05 章「固定否定視窗的限制」。

P = 3、N = 1、L = 100 時,net tone 與 coverage 是?
100 × (3 − 1) / 100 = 2;100 × (3 + 1) / 100 = 4。投影片 32
unmatched 與 balanced 的 net tone 都是 0,差在哪?
Zero can mean no matches or cancellation; neither proves neutrality。投影片 34
05 · 計分

否定詞、前處理與 Denny & Spirling

bag-of-words 字典不懂「not good」。保留 not 只是第一步,還需要一條用到它的規則;而每個前處理選擇(停用詞、詞形)都可能改變結果——Denny & Spirling 的宣言案例顯示,128 種前處理組合會排出 12 種不同順序。

C11:一個刻意的情緒失敗 投影片 35–36

預測:保留 not 會讓第二句變成負面嗎?

R · C11(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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"  
  1. 字典比對:兩句都比對到 good(positive = 1、negative = 0)。規則沒有用 not 來反轉。
  2. 移除停用詞之後:not 在 stopwords("en") 裡,被刪掉了;兩句的 token 變得一模一樣:"policy" "good"。
投影片 36 的結論

保留否定詞,然後加一條處理它的規則。

互動:一個固定的否定視窗能做到哪裡?

🚫否定視窗規則補充(非講義內容)· 玩具直覺型

句子取自投影片 37 的四種困難情況,外加 C11 的兩句。字典=teaching_affect.dic 加上 reject(負面,為了示範第二句而加,非講義字典內容)。Rauh(2018)的做法是「直接的兩字否定規則」(投影片 57);這裡的視窗=1 最接近它。

固定否定視窗的限制 投影片 37

  • 「Not good」和「not only good but excellent」不一樣。
  • 「I reject the claim that this is a failure」含有負面字。
  • 引述別人的批評,不一定是講者自己的看法。
  • 長距離的否定可能超出簡單的字數視窗。

規則能改善基準線,但不能解決每一句。投影片 37

前處理必須配合字典 投影片 38

  • 不同停用詞表會刪掉文本中不同比例的字。
  • 否定詞有意義時要保留。
  • 字典條目要對齊你選擇的詞形(例如有沒有 stemming/lemmatisation)。
  • 檢查每個前處理選擇丟掉了什麼。

投影片 38 的圖(Hvitfeldt & Silge 2022):每篇故事三個點、對應三份停用詞表;X = 總字數、Y = 被移除字詞的百分比。同一份文本,不同表移除的比例不同。

🧹quanteda 的 stopwords("en") 會刪掉哪些字?真實資料 · 本機匯出的停用詞表

案例:從宣言定位政黨(Denny & Spirling 2018) 投影片 39–41

  • 問題:宣言用語能把政黨放在左右量尺上嗎?資料:8 份英國政黨宣言,1983–1997;模型:Wordfish(從字數估計位置)。投影片 39
  • 同樣 8 份宣言、同一個 Wordfish 模型,128 種前處理規格,排出12 種不同的文件順序;黑色格子=與作者事前排序不一致。投影片 40
研究主張這個案例能顯示什麼(投影片 41)
字彙可以把政黨放上量尺Wordfish 從字數估計相對位置
排序在合理選擇下穩健要檢查:這個例子產生 12 種排序
模型解釋政黨為何改變這是因果問題,需要不同的研究設計

帶回字典:實質比較在合理的計分選擇下還站得住嗎?(下一章 C12/C15 就是在做這件事。)投影片 41

C11 中,對兩句做 tokens_remove(stopwords("en")) 後會怎樣?
not is deleted. The two token lists are now identical。投影片 36
Denny & Spirling 的宣言案例主要告訴我們?
Do substantive comparisons survive reasonable scoring choices?投影片 40–41
06 · 計分

字典修訂與敏感度(C12、C15)

這一章的研究構念換成能源政策注意力(不是情緒)。Dictionaries/energy_policy.csv 有兩個版本:v1 寬、v2 窄。改字典會改分數——但改了之後是不是更好,只有人工判斷能回答。

C12:字典修訂改善了測量嗎? 投影片 42

先預測:哪個版本會標記更多發言?

R · C12(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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 的螢光筆

🖍發言瀏覽器+字典螢光筆真實資料 · 335 篇 discovery 發言
你的判斷(依 Lab handout 的標記規則):

樣本:本機以 set.seed(719) 從 discovery 發言中抽 300 篇(60–700 tokens),再加入 v2 每千字比對最高的 40 篇(≤ 900 tokens)以確保有能源相關發言,去重後 335 篇——不是隨機樣本,不能拿來估計全語料的 precision。比對邏輯同第 07 章驗證台(JS 模仿 tokens_lookup());每千字比率的分母用 JS 的切字數,與 R 的 tokens 欄可能有小差異,下方同時列出 R 的 token 數。

C15:視覺化字典敏感度 投影片 43–44

dev 是 C12 建的表:一列一篇發言,共 4,950 篇;v1_per1000、v2_per1000 是兩個版本每千字的比對數。

R · C15(W4/classroom/W4_classroom.R)
# 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()
C15 本機重繪:v1 vs v2 每千字比對數
本機執行 C15 產生的圖(ggplot2 4.0.3)。一點=一篇發言;在虛線上=不變;線下=v2 比對較少;線上=v2 比對較多。本機計數:4,950 篇中 4,096 篇在虛線上(其中 4,046 篇兩版都是 0,全疊在原點)、841 篇在線下、13 篇在線上。投影片 44
🎯互動散布圖:v1 vs v2真實資料 · 4,950 篇
投影片 44 的結論

重疊的點可能藏住很多篇。分數改變顯示的是敏感度,不是哪一版更有效度。

延伸:用 v1/v2 比較政黨(Lab 選做段落)

workflow.R 也算了政黨層級的比率:先加總、再相除(ratio of group totals),不是每篇比率的平均。注意 party_rates 用的是全部 5,000 篇(policy_scores),不只是 4,950 篇 discovery。

🏛政黨每千字能源比對數真實資料 · party_rates
依 token 總數由多到少排列。v1 與 v2 的政黨排序是否一樣?如果不一樣,這正是投影片 41 問的「實質比較在合理選擇下站得住嗎?」小黨的 token 數很少,比率不穩。
C15 散布圖中,有比對的發言大多落在虛線下方(本機:841 篇在線下、13 篇在線上)。最合理的解讀?
Changed scores show sensitivity, not which dictionary is more valid。投影片 44
07 · 驗證

人工基準、kappa、precision/recall

驗證要有人工判斷當基準。這一章先看人與人之間一致嗎(C13,kappa),再看字典和人一致嗎(C14,precision/recall/F1),最後用 24 句教學句子實作「開發 → 凍結 → 測試」。

人工基準 投影片 45

  • 寫一份 codebook,附正面、負面與模糊的例子。
  • 可行時,讓編碼者不知道字典的預測。
  • 記錄分歧與裁決程序。
  • 編碼單位要對齊分數的用途。

人工標記是要被檢視的證據,不是不容質疑的真相。投影片 45

該驗證哪些文本? 投影片 46

  • 同時納入有比對與沒比對的段落。
  • 涵蓋重要日期、群體與不同長度的文件。
  • 最終表現估計要用沒碰過的樣本。
  • 罕見或模糊的案例另外檢查,用於診斷。

一堆簡單例子不能建立全語料的表現。投影片 46

C13:兩位人工編碼者的一致性 投影片 47

R · C13(W4/classroom/W4_classroom.R)
# 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
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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。

🤝Kappa 計算機玩具直覺型 · 預設=C13
B = 1
B = 0
A = 1
A = 0

補充(非講義內容):試著讓兩人都把幾乎所有文本標成 0(例如 0, 1, 1, 18)——一致率很高,但 kappa 會掉很多。

議題偵測的混淆矩陣 投影片 48

20 個示範段落人工:相關人工:不相關
字典:有比對6 true positives2 false positives
字典:沒比對4 false negatives8 true negatives

單位是段落,不是字典裡的字。

C14:precision 與 recall 投影片 49–50

跑程式前先用上面的表手算一次。

R · C14(W4/classroom/W4_classroom.R)
# 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)
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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)。
投影片 50

漏掉的案例很重要:只讀字典比對到的段落,無法得知 recall。

🎛Precision/Recall 計算機玩具直覺型 · 預設=投影片 48

試試看投影片 49 的問題:如果只讀字典有比對的 TP + FP 段落,你能算出 FN 嗎?

互動:開發 → 凍結 → 測試(24 句教學句子) 投影片 95

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。只是示範用的算術,不是在國會語料上的表現估計。投影片 95
R console output(本機實跑 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
🧪字典驗證台真實資料(課程 Data/)+練習型
或自己改字典條目(每行一條,可用 *、片語):
規則:先只看 development 調整;滿意後按「凍結」,再切到 test。凍結前偷看 test 也行,但這裡會記下來。

比對邏輯:保留標點、不分大小寫、glob 萬用字元、片語須連續(模仿 policy_counts());載入 v1/v2 時,每句的預測會與 R 實跑結果核對,表格最右欄顯示「R」的預測。

評估連續的情緒分數 投影片 51

  • 把分數對人工評分畫圖。
  • 檢查群組平均與個別分歧。
  • 檢查沒比對到的文本、被壓縮的範圍與極端值。
  • 比較不同群體與文類下的表現。
📈相關 ≠ 一致玩具直覺型 · 投影片 51 的例子

驗證要對應主張的層次 投影片 52

主張需要的證據
這一句是負面的句子層級的一致性
這一群相對比較正面群體層級的測量效度
情緒隨時間改變跨時期穩定的測量
各國衝突程度不同可比較的測量與制度脈絡
⚖️主張判斷:這份證據夠支持這個主張嗎?練習型
C13 的兩位編碼者一致率 80%,kappa 只有 0.60,因為?
(0.8 − 0.5) / (1 − 0.5) = 0.6。投影片 47
只讀字典比對到的段落,可以估計哪一個?
Missed cases matter: reading only matched passages cannot tell us recall。投影片 50
分數 1, 2, 3 與 11, 12, 13 的相關係數是 1。這表示?
Two scores can rise together but still disagree。投影片 51
08 · 研究案例

案例:Boyle、Rauh、Proksch

三個已發表研究,各自示範字典測量的一個環節:自建字典+留出樣本測試(Boyle et al. 2025)、改編字典+人工驗證(Rauh 2018)、翻譯字典+群體層級驗證+實質分析(Proksch et al. 2019)。以下內容皆依投影片整理(三篇全文不在 repo 內,見第 12 章)。

能源研究的政策相關性(Boyle et al. 2025) 投影片 53–55

  • 問題:哪些摘要在傳達政策相關性?資料:270,537 篇摘要、100 份期刊、2010–2023;用自訂字典辨識相關陳述。表達的相關性 ≠ 政策實際採用。投影片 53
  • 單位:一篇摘要(是否含政策相關陳述)。開發:從政策詞開始,讀 400 篇雙人編碼摘要找出更多詞;精修:只保留能提升開發集正類 F1 的新增詞;測試:在另外 200 篇人工編碼、未參與調整的摘要上評估。
  • 報告的平均 F1:開發 0.90/留出 0.86。老師的研究過程註記:一開始試過 fine-tune transformers,結果不理想。投影片 54
  • 約 15% 摘要被分類為政策相關;只有 8% 明確提到 policy/policies。期刊宗旨明確提到政策者:26.7%;沒有提到者:3.7%。這是描述性的文本型態,不是政策採用的證據。投影片 55

對照第 02 章投影片 24:這正是「discovery → 凍結 → held-out」的實際研究版本。開發集 F1 比留出集高,是預期中的現象。

德國政治語言的情緒字典(Rauh 2018) 投影片 56–60

步驟研究做了什麼(投影片 57)
Dictionary合併 SentiWS 與 GermanPolarityClues;人工審查詞條
Context加上直接的兩字否定規則
Score正面減負面比對數,除以保留的詞數
Validation三人編碼 1,500 句抽樣的 Bundestag 句子
  • 編碼者一致性:3 位編碼者、1,500 句;完全一致 59.1%;ordinal alpha .675。一致性不等於效度。投影片 58
  • 比較三個字典在人工評分類別上的分數;正面類別分得比較開。區間顯示的是群組平均的不確定性,不是分類準確率。投影片 59
  • 結果:正面評價比負面評價容易還原。用途:比較政治文本中評價語言的已檢驗指標。限制:分數集中在 0 附近,沒有不證自明的數值單位。這個研究驗證的是測量,不解釋政治人物為何變得更正面。投影片 60

情緒與立法共識(Proksch et al. 2019) 投影片 61–65

問題:在野黨的語氣是否反映跨黨共識?更正面的在野黨語言是否與法案無異議通過相關?投影片 61–62

  1. 蒐集約 26,000 篇演說,涉及 871 個德國政府法案,2005–2017。
  2. 用翻譯的 Lexicoder 情緒字典比對正負面字。
  3. 依政黨與法案加總:log((P + 0.5) / (N + 0.5))。
  4. 把法案層級的情緒放進「無異議通過」的 logistic 迴歸。
  • 人工驗證:300 段、每段兩個人工評分;以講者群組比較標準化分數;報告的群組層級相關約 0.9——這不是 90% 分類準確率。投影片 63
  • 翻譯本身是測量決策:譯詞的政治用法可能不同、可能有多個對應、詞形與斷詞會影響比對;各語言要分開驗證。相同的類別名稱不保證數值尺度可比。投影片 64
  • 迴歸:814 個法案;三個模型係數都是正的,只有模型 (3) 顯著。這是關聯,不是語氣的因果效果。投影片 65
➗log ratio vs net tone玩具直覺型 · 公式取自投影片 32、62

補充(非講義內容):+0.5 讓 P 或 N 為 0 時仍可取對數;log ratio 不用 L 當分母,所以「長度加倍、比對也加倍」時分數不變,而 net tone 也不變;但只加長度不加比對時,net tone 會變小,log ratio 不變。試試看。

情緒、立場與衝突 投影片 66

概念證據必須建立什麼
Sentiment某個定義好的單位中的評價語言
Stance對特定目標的支持或反對
Conflict行動者或立場之間的實質關係

負面字可以描述社會問題,而不是在攻擊另一個政黨。

翻牌卡:三個案例的關鍵數字

🃏先想答案,再點卡片翻面練習型
Proksch et al. 報告人工與自動分數在群組層級相關約 0.9。正確解讀?
This is not 90% classification accuracy。投影片 63
Boyle et al. 的開發集 F1 0.90、留出集 0.86。為什麼要報兩個?
Test: evaluate on 200 other human-coded abstracts, kept out of tuning。投影片 54
09 · 延伸應用

LIWC、自訂字典與競選承諾

LIWC 是最常見的「類別百分比」工具;但軟體、官方字典與我們自己的 quanteda 字典是三件不同的事。接著用 Eichorst & Lin(2019)的概念做一個兩句話的「具體 vs 模糊」例子,最後看兩個中文 LIWC 研究。

LIWC:它在量什麼? 投影片 67

  • LIWC = Linguistic Inquiry and Word Count:把語言對應到預先定義的字典類別。
  • 類別包括代名詞、情緒、社會歷程等;多數類別分數是佔全文字數的百分比。例:100 字中有 4 個類別比對 = 4%。
  • 類別百分比量的是用字;詮釋仍需要驗證。

LIWC 與 quanteda:角色分開 投影片 68

資源角色取得方式
LIWC 應用程式執行內建或自訂字典授權軟體
官方 LIWC 字典專有的詞—類別資源受授權條款限制
quanteda + 我們的字典在 R 裡用自己的規則比對不需購買 LIWC

匯入一個檔案,不代表你取得了使用該字典的授權。本週的 teaching_affect.dic 只是借用 LIWC 的檔案格式(% 包住類別編號,下面每行「字 + 類別編號」)。

C16:用 quanteda 套用我們的字典 投影片 69

R · C16(W4/classroom/W4_classroom.R)
# 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
R console output(本機實跑 W4_classroom.R:R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)
> 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) 投影片 70–71

  • 問題:政黨什麼時候會做出具體的競選陳述?文本:英文政黨綱領;比較執政地位與經濟表現。
  • 字詞密度圖:每欄是一份政黨綱領、每列是一個字典詞;顏色越深=對數次數越大,白色=0。投影片 71

兩句話的字典例子 投影片 72–74

老師的 examples/W4_campaign_simple.R,本機執行:

R console output(本機實跑 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。投影片 74
  • 改編自 Eichorst & Lin(2019):原論文分母不含停用詞,並把差值重新縮放到 0–1;這個例子兩者都沒做。
📣具體 vs 模糊計分器玩具直覺型 · 預設=投影片 72

第三句對應投影片 73 的「Try: Add not before guarantee」:計數不變(仍是 concrete 1),但 L 變成 7。

中文 LIWC:兩個研究 投影片 75–76

  • Lin(2023):中文的回顧文章,介紹字典類別與用字率,回顧運動傷害、自我效能與運動傳播的研究。討論題:語言能揭露一個隊伍的什麼?投影片 75
  • Lin et al.(2020):類別能區分情緒脈絡嗎?資料:PTT 的 50 篇 Hate 與 50 篇 Sad 貼文;憤怒詞 2.00% vs 0.88%,Cohen’s d = 0.61。群體差異不是個人診斷。投影片 76
在 quanteda 裡用 format = "LIWC" 讀一個 .dic 檔,代表?
Importing a file does not grant a license to use its dictionary。投影片 68–69
「We will not guarantee better public services.」用投影片 72 的字典,教學分數?
字典沒有否定規則;100 × (1 − 0) / 7 ≈ 14.29。投影片 73–74
10 · 延伸

字典之外:POS、TextRank、NER、LLM

這些工具幫我們找候選詞或找名稱,但都不會自動驗證字典。選讀延伸(O01、TextRank、Flair)需要下載模型;本機能跑的照實貼輸出,跑不了的照實說。

POS 標註(UDPipe) 投影片 77–80

選讀延伸:回到「找候選詞」,現在是 POS → 候選詞 → 人工審查。

R · examples/W4_pos_simple.R
# 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")]
R console output(本機實跑;udpipe english-ewt 模型)
> 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:排名候選詞 投影片 81–83

資料: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 被標成名詞。

R · examples/W4_keywords_real.R
# 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.
R console output(本機實跑)
> 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
本機 TextRank 與投影片 82–83 對不上(並列說明)
名次投影片 82(老師的執行)本機(udpipe 0.8.16、textrank 0.3.1、english-ewt 2.5)
1new 0.0161new 0.0125
2same 0.0096we 0.0122
3endure 0.0095require 0.0112
4nation 0.0094nation 0.0090
5common 0.0092common 0.0089
6hard 0.0083these 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 選讀) 投影片 84–86

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 可以提出候選詞 投影片 87

種子概念 → 建議詞 → 語料中的例子 → 研究者審查。Embeddings 能建議相關說法;LLM 能提出變體或整理候選清單;但也可能冒出反義詞與無關聯想。保留一個獨立的人工基準:這些工具協助開發字典,不能認證效度。

延伸到中文文本 投影片 88

選擇例子
斷詞(Segmentation)相關的表達有沒有被切壞?
字形正規化繁簡、異體字是否適當合併?
實體別名縮寫有沒有連到正確的機構?
否定與脈絡這個片語表達支持、批評還是引述?

要在專案所用的語言與政治場域內驗證。補充(非講義內容):例如「不」「沒有」「未必」在中文常緊貼在評價詞前,斷詞器把「不好」切成一個詞或兩個詞,會直接決定字典能不能比對到「好」。

五句話、三種標記方法 投影片 89–90

先自己標,再看字典怎麼標:

✍️你 vs 字典練習型 · 字典結果=本機執行 five_sentence_sentiment.R
R console output(本機實跑 examples/five_sentence_sentiment.R)
> 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.」更快的標記能回答研究問題嗎?還需要哪些驗證?

TextRank 把 new 排第一。最合理的下一步?
High centrality does not establish relevance。投影片 82
「Excellent, another tax increase.」字典標為 positive,問題在於?
Check negation and possible irony。投影片 89
11 · 實作

回到專題+課後 Lab 四個任務

投影片最後一段把全部概念收回到「寫 methods section」與「你自己的專題」。接著是課後 Lab(45–60 分鐘、不計分、不必繳交)的四個任務;以下輸出都是本機執行 W4/lab/Lab_Session_W4.R 與 answers/Lab_Session_W4_Answers.R 的結果。

Methods section 應該報告什麼 投影片 91

  • 語料範圍、來源與分析單位。
  • 字典來源、版本、語言與修改。
  • 比對、前處理、分母與零的規則。
  • 人工驗證的設計、結果與剩下的錯誤。
  • 足以稽核整個流程的程式碼與取得資訊。

把概念套到研究專題 投影片 92–93

投影片 92 的句型:我想量 …,而不只是數 …;我的分析單位是 …;一個可能的 false positive 是 …;一個可能的 false negative 是 …;我會用 … 驗證這個測量。開場問題的延伸:還需要哪些規則才能辨識對家戶狀況的負面評價?投影片 93:字典適合你的專案嗎?列兩個優點、兩個限制;速度、透明度與脈絡敏感度怎麼取捨?

第 14 章有一個研究計畫填寫器,把這些句型整理成 Markdown。

O02:你自己的政策字典(選做挑戰) 投影片 94

加入一個有理由的能源政策詞,然後兩人一組:找一段支持它的段落、一段可能的 false positive。

R · O02(投影片 94;不在 W4_classroom.R 內,本機未另行執行)
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:讀字典、看比對 投影片 97

Setup 區塊(和 C01 相同,會 source("workflow.R"))跑完後,先讀 .dic 原始檔:

R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 2 個程式區塊)
> 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
R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 3 個程式區塊)
> 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
R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 4 個程式區塊)
> 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 增加了分母,不是因為規則認出了否定。

R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 5 個程式區塊)
> # 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     TRUE

Lab 任務 2:改一條能源政策規則

標記規則(Lab handout 第 2 節)
  • 1 — 相關:討論能源生產、供應、價格、負擔能力或轉型(如電費、暖氣費、再生能源、煤礦關閉)。有一段實質討論就夠,講者不必支持政策。
  • 0 — 不相關:政治上的 power、無關的立法 bill、個人的 energy、催淚 gas 都不算。一般氣候討論只有連到能源時才算。
  • 不確定:留空、寫下原因、計分前討論。不要把不確定當成 0。
R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 6 個程式區塊)
> 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                            
R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 7 個程式區塊)
> 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 …〔以下略〕
R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 8 個程式區塊)
> 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     0

answers 的解讀:wind 從 0 變 1,authority 從 1 變 0——這個修改修好了兩個例子。接著要檢查其他句子還剩哪些錯。

R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 9 個程式區塊)
> 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      0

Lab 任務 3:檢查開發集錯誤

R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 10 個程式區塊)
> # 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
R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 11 個程式區塊)
> 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  0

worked answers 只列出 v1 判錯的開發句:

R console output(本機實跑 answers/Lab_Session_W4_Answers.R)
> 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  1

answers 的說明:開發句顯示為什麼可能要拿掉單獨的 power、gas、bill*,並加入再生能源、太陽能板、風場與化石燃料的說法。第 07 章的「字典驗證台」可以直接互動做這一步。

Lab 任務 4:固定 v2,在測試句上算 precision/recall/F1

R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 13 個程式區塊)
> 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
R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 14 個程式區塊)
> # 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 
R console output(本機實跑 answers/Lab_Session_W4_Answers.R)
> 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 預習:五篇文本、一個困難決定 投影片 96

W5(10 月 9 日)放假;W6(10 月 16 日)談人工編碼與分類。現在先用簡短 codebook 標五篇、說明一個不確定的決定、把字典預測分開保存;約 10 分鐘,不用訓練模型也不用上傳。

R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 15 個程式區塊)
> 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                                                                                                                                                                                                                                                                                                                                                                                                                …〔以下略〕
🏷五篇開發發言標記單練習型 · 文本=coding_template 前五篇(本機實跑,set.seed(719104))

選做:政黨比較

R console output(本機實跑 W4/lab/Lab_Session_W4.R,第 16 個程式區塊)
> # 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 一致(同樣是先加總再相除)。

執行清單

✅課堂 C01–C16 + Lab 任務勾選你在自己電腦上跑過的
Lab 任務 4 看到 v2 漏掉兩句,想加 coal。正確的做法?
Using test information to revise the dictionary needs a fresh test set(answers)。投影片 95
12 · 文獻導讀

文獻導讀

指定閱讀三篇(投影片 98)。這三篇的全文都不在課程 repo 內,所以下面的卡片只整理投影片的陳述(附投影片頁碼),不引用論文頁碼。repo 裡唯一相關的合法全文是 W1 的 Grimmer & Stewart(2013),它的字典段落附論文頁碼。

Denny & Spirling (2018) 投影片 39–41、98

書目“Text Preprocessing for Unsupervised Learning: Why It Matters, When It Misleads, and What to Do about It.” Political Analysis 26(2): 168–189.
本週用到的論點同樣 8 份英國宣言(1983–1997)、同一個 Wordfish 模型,128 種前處理規格排出 12 種不同順序(投影片 40)。
帶回字典實質比較在合理的計分選擇下站得住嗎?(投影片 41;本教材第 05–06 章)
全文不在 repo。未取得全文,無法提供論文頁碼。

Rauh (2018) 投影片 56–60、98

書目“Validating a Sentiment Dictionary for German Political Language: A Workbench Note.” Journal of Information Technology & Politics 15(4): 319–343.
設計合併 SentiWS 與 GermanPolarityClues、人工審查、兩字否定規則;(正 − 負) / 保留詞數;3 位編碼者 1,500 句 Bundestag 句子(投影片 57)。
關鍵數字完全一致 59.1%、ordinal alpha .675(投影片 58);正面評價比負面容易還原;分數集中在 0 附近(投影片 60)。
全文不在 repo。未取得全文,無法提供論文頁碼。

Proksch, Lowe, Wäckerle & Soroka (2019) 投影片 61–66、98

書目“Multilingual Sentiment Analysis: A New Approach to Measuring Conflict in Legislative Speeches.” Legislative Studies Quarterly 44(1): 97–131.
設計約 26,000 篇演說、871 個德國政府法案(2005–2017);翻譯 Lexicoder;log((P + 0.5) / (N + 0.5));logistic 迴歸(814 個法案)(投影片 62、65)。
驗證300 段、每段兩個人工評分;群組層級相關約 0.9,不是 90% 準確率(投影片 63)。翻譯是測量決策(投影片 64)。
全文不在 repo。未取得全文,無法提供論文頁碼。

Grimmer & Stewart (2013)(repo:W1/papers/Grimmer2013.pdf)

書目“Text as Data: The Promise and Pitfalls of Automatic Content Analysis Methods for Political Texts.” Political Analysis 21(3): 267–297。投影片 7、9、11 引用。
字典的定義(p. 274)字典用關鍵字出現的比率把文件分類,或衡量文件屬於某類別的程度;最簡單的 tone 是每個字給 +1/−1,再除以文件字數 Ni——就是第 04 章 net tone 的形式(差在乘 100)。
領域特定性(pp. 274–275)字典的分數必須貼近字在該脈絡的用法;作者引 Loughran & McDonald(2011):tax、cost、crude(oil)、cancer 在其他脈絡帶負面意涵,在公司財報裡可能帶正面意涵;把一個領域建的字典套到另一個領域,可能出現嚴重錯誤。
驗證(p. 275;原則 4 見 p. 271)作者指出字典測量「rarely validated」,建議要嘛把問題簡化成二元分類、用人工黃金標準驗證,要嘛像非監督方法一樣多面向驗證。原則 4:“Validate, Validate, Validate”。

延伸閱讀與軟體(投影片 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 取得全文。

13 · 收尾

常見陷阱與詞彙表

十個常見陷阱

把「提到」當成「評價」

提到 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)。

翻牌卡:公式與定義

🃏點卡片翻面練習型

詞彙表

14 · 收尾

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

我的進度

總複習(20 題)

研究計畫填寫器 投影片 91–93

📝我的字典測量計畫練習型 · 匯出 Markdown,可接到期末專題
Markdown

參考文獻(依投影片 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.
本教材依據 NTLDEV 7191 W4 投影片(Yen-Chieh Liao 廖彥傑,2026-10-02;PDF 共 99 頁,Last compiled 2026-10-08)、W4/classroom/W4_classroom.R、workflow.R、examples/、W4/lab/Lab_Session_W4.R 與 answers/ 製作。R 輸出為本機重新執行(R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、irr 0.85、ggplot2 4.0.3;Linux aarch64)。三篇指定閱讀全文不在 repo,導讀卡依投影片整理。標示「補充(非講義內容)」的段落與玩具示範為額外說明。製作日期 2026-11-06。
NTLDEV 7191 Text as Data · W4 互動自學教材 · 依據 2026-10-02 投影片製作(2026-11-06)