科研 Skill
文本数据定量分析
alterlab-text-as-data
Analyzes text as social-science data with topic modeling, embeddings, and validated dictionary or classification methods. Use for computational text analysis beyond a keyword count.
SKILL.md
Text-as-Data — Match the Method to the Inferential Goal
Skill type: ANALYSIS MODULE. Turns a corpus into measurements. The discipline is choosing by goal — discovery (what themes exist?), measurement (how much of concept X?), or prediction (label new documents) — and validating that a topic solution is reliable, not a single lucky stochastic run.
Core Mission
PICK BY GOAL: DISCOVERY vs MEASUREMENT vs PREDICTION. THEN VALIDATE THE TOPICS — ONE RUN IS NOT A RESULT.
When to Use This Skill
- "Run topic modeling on my corpus (BERTopic / LDA)."
- "Measure how much each document expresses concept X (dictionary/lexicon)."
- "Embed my documents and cluster / compare them."
- "Classify these texts into categories."
Does NOT Trigger
| The request is really about… | Route to | Why not this skill |
|---|---|---|
| Training / fine-tuning a transformer model | alterlab-transformers | Model training, not corpus measurement. |
| Humanities close-reading / annotation of texts | alterlab-digital-humanities | Interpretive, not quantitative text-as-data. |
| Whether a text method fits the question at all | alterlab-ssci-design-gate | Design routing, upstream. |
| Plain tabular statistics | alterlab-statistical-analysis | No text. |
Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-transformers) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.
Running the code. In Claude Code, run analysis code in a throwaway environment instead of installing packages: uv run --python ">=3.11" --with "bertopic>=0.16" --with "sentence-transformers>=2.2" python topics.py. This needs no install approval and leaves the user's environment untouched. If uv or the network is unavailable, say so and hand over the script; never report results you did not compute.
Method by goal (verified stack, pinned)
| Goal | Method | Verified call |
|---|---|---|
| Discovery (emergent themes, contextual) | BERTopic (v0.17) | from bertopic import BERTopic; topics, probs = BERTopic().fit_transform(docs); get_topic_info(), get_topic(0). Plug embeddings via embedding_model=SentenceTransformer("all-MiniLM-L6-v2"), a vectorizer_model=CountVectorizer(min_df=10). |
| Discovery (bag-of-words, classic) | LDA / NMF | sklearn: LatentDirichletAllocation(n_components=k).fit(CountVectorizer().fit_transform(docs)); or gensim LdaModel(corpus, num_topics=k, id2word=dictionary). |
| Topic quality | coherence | gensim CoherenceModel(model=lda, texts=tok, dictionary=d, coherence="c_v").get_coherence(). |
| Measurement (how much of concept X) | dictionary / lexicon | count validated lexicon terms; report reliability and validate against hand-coding. |
| Embeddings / similarity | sentence-transformers (v6) | SentenceTransformer("all-MiniLM-L6-v2").encode(texts) → cluster / cosine-compare. |
| Prediction (label documents) | supervised | TfidfVectorizer() → a sklearn classifier; report held-out F1, not in-sample fit. |
| Linguistic features (POS, entities) | spaCy (v3) | nlp = spacy.load("en_core_web_sm"); doc = nlp(text). |
Method-selection helper (stdlib): scripts/text_method_router.py. Full patterns, preprocessing,
and the topic-reliability procedure: references/text_stack.md.
The reliability discipline (topic models are stochastic)
LDA (and, to a lesser degree, BERTopic via UMAP) gives different topics on different runs. A single run is not a result. Required:
- Replicate across seeds/runs; align topics across runs (e.g. Hungarian matching) and score stability (top-word overlap, RBO); report a prototype (most-representative) solution.
- Coherence, not just perplexity — choose K by
c_vcoherence and human readability, not log-likelihood alone. - Determinism where possible — fix
random_state(sklearn LDA) and UMAP'srandom_state(BERTopic) for reproducibility; still report stability across different seeds. - Validate measurement — a dictionary/topic used as a measure of a concept needs validation against human coding (precision/recall or correlation), exactly like any other instrument.
Output Template
GOAL: discovery | measurement | prediction
METHOD: <BERTopic / LDA / dictionary / embeddings / supervised> + why it matches the goal
MODEL: <call + K selection by coherence; embedding/vectorizer choices>
RELIABILITY: <seeds run; topic stability; coherence c_v; determinism settings>
VALIDATION: <if used as a measure: agreement with human coding>
CLAIM SCOPE: descriptive/measurement of the corpus; generalization scoped to the corpus/sampling
References
references/text_stack.md— BERTopic/LDA/gensim/spaCy/embeddings patterns, preprocessing, topic-reliability procedure.scripts/text_method_router.py— stdlib router from goal + corpus features to the right method.
Part of the AlterLab Academic Skills suite.
示例提示词
我想对这批社交媒体文本做主题建模,区分不同话语主题。
所属插件
安装该插件会一并获得同领域的 58 个 Skill / MCP。
同插件的其他科研 Skill
- Mesa社会主体建模Builds Mesa agent-based models of opinion dynamics, segregation, social contagion, and network diffusion. Use when simulating emergent social behavior from agent rules.
- Mesa3主体建模引擎Builds agent-based models with the Mesa 3 AgentSet API, cell spaces, and batch_run sweeps for segregation, diffusion, and cooperation. Use for a Mesa 3.x ABM build or debug.
- 观察数据因果推断Estimates causal effects with DiD, IV, RDD, panel fixed effects, and propensity scores via statsmodels, linearmodels, DoWhy, and EconML. Use for observational or quasi-experimental causal estimation.
- 效应量元分析Pools effect sizes across studies with fixed/random-effects models, heterogeneity stats, forest/funnel plots, and publication-bias tests. Use for a systematic review’s quantitative synthesis.
- 缺失数据插补处理Handles missing data by naming the MCAR/MAR/MNAR mechanism, then applying multiple imputation (MICE) or FIML instead of single imputation. Use when a dataset has missing values to treat.
- 多层线性混合模型Fits mixed-effects/multilevel models (random slopes, ICC, GLMMs) for nested or longitudinal data via statsmodels, bambi, or R lme4/brms. Use for grouped data with within- vs between-cluster questions.
- 定性比较分析QCARuns crisp-, multi-value, and fuzzy-set Qualitative Comparative Analysis via R’s QCA package. Use for configurational or necessary/sufficient-condition research.
- 质性编码与主题分析Builds codebooks and computes intercoder reliability (Krippendorff’s alpha, kappa) for thematic or content coding, including human-vs-LLM double coding. Use when coding text or reporting reliability.
- 社会网络结构分析Computes network centrality, community detection, and ERGM inferential models matched to the research question via networkx/igraph. Use for social-network analysis beyond basic visualization.
- 社科研究设计把关Routes a study to its research design (experiment, quasi-experiment, observational, qualitative) and pins the identifying assumption first. Use when choosing a study design.
- 社科推论结论审核Audits inferential claims against the design before publication: unwarranted causal language, p-value/CI misreadings, and multiple-comparison issues. Use when checking a results section.
- 量表测量质量把关Checks that a scale’s reliability, validity, and measurement invariance are established before trusting or comparing it across groups. Use when adopting or reporting a survey instrument.
- 社科研究流程总控Coordinates a study through design, measurement, sampling, analysis, and inference gates with a shared Design Passport. Use for an end-to-end methodology review of a whole study.
- 质性研究可信度把关Gates qualitative trustworthiness before write-up: positionality, credibility, transferability, dependability, confirmability per Lincoln and Guba. Use before writing ethnographic findings.
- 抽样方法与样本量把关Checks that the sampling frame, method, and size match the inference paradigm before data collection. Use when planning recruitment or judging sample generalization.
- 复杂抽样调查分析Analyzes complex-sample survey data with design-based inference: weights, strata, PSUs, and calibration via Python svy or R survey/srvyr. Use for weighted surveys like GSS, ANES, or DHS.
- 政策议题框架分析Runs anthropological framing and metaphor analysis on contested-policy documents, producing actor-attributed CSVs for NVivo import. Use for policy-framing or metaphor-analysis coding.
- 跨国比较政治分析Merges QoG, Polity5, and Freedom House data and runs cross-sectional OLS with fixed effects and regime classification. Use for comparative political-institution research.
- 计算社会学方法Covers social-media data collection, bot detection, network homophily, echo-chamber analysis, and conjoint survey experiments. Use for large-scale digital-trace sociology research.
- 冲突事件数据分析Downloads ACLED/UCDP conflict data and runs spatio-temporal clustering, conflict-onset logit panels, and fatality estimation. Use for quantitative armed-conflict research.
- 联合分析调查实验Designs conjoint survey experiments and estimates AMCEs via OLS, marginal means, and respondent-level heterogeneity. Use when designing or analyzing a choice-based conjoint experiment.
- 统计方法教学规范Defines the baseline statistical teaching and reproducibility standards shared across this analysis skill family. Use as the methodology reference other skills in the family build on.
- 人口统计方法分析Computes life tables, Leslie-matrix population projections, Lee-Carter mortality forecasts, and Kitagawa decomposition. Use for formal demographic analysis of mortality or population structure.
- 描述性统计分析Produces summary statistics, distributions, correlations, and cross-tabs for exploratory analysis. Use when summarizing a dataset before modeling or reporting.
常见问题
文本数据定量分析能做什么?
Analyzes text as social-science data with topic modeling, embeddings, and validated dictionary or classification methods. Use for computational text analysis beyond a keyword count。
如何安装文本数据定量分析?
在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「文本数据定量分析」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。
文本数据定量分析需要哪些权限?
该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。
文本数据定量分析经过官方审核吗?
是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。