COMP5310 — 数据科学期末复习 & 模拟测试

Semester 1, 2026 · 基于课件 02–13 + Sample 2026 + 2017/24S1 真题 · 5 sections / 100 分(25 MCQ 40分 + Q2–Q5 各15分)

📖 复习 (Review)
📝 模拟测试 (Mock Test)
📖 用法:每个知识点都是中文 + English 对照。中文理解概念,英文用于考场表达(考卷是英文)。绿框=举例,黄框=易错陷阱。
Each point is bilingual: Chinese to understand, English for the exam. Green = examples, yellow = common traps.
Q1 · 选择题 40分(覆盖全部主题)

Week 1 · 数据科学导论 (Introduction to Data Science)

1. 数据科学工作流 (Data Science Workflow)

数据科学是一个循环迭代的过程,真题考过让你给步骤排序。
Data science is an iterative pipeline; past papers ask you to put the steps in order.

  1. Data Acquisition 数据获取 — 从数据库、API、网页爬取、传感器收集原始数据。
    Collect raw data from databases, APIs, web scraping, sensors.
  2. Data Storage 数据存储 — 把数据存进数据库或数据仓库。
    Store the data in a database or data warehouse.
  3. Data Cleaning & Transformation 清洗与转换 (ETL) — 去重、补缺失、统一格式与单位。
    Remove duplicates, fill missing values, standardise formats and units.
  4. Exploratory Data Analysis (EDA) 探索性分析 — 画图、看分布、找规律和异常。
    Plot charts, inspect distributions, find patterns and anomalies.
  5. Modelling & Predictive Analysis 建模与预测 — 训练回归/分类/聚类模型。
    Train regression / classification / clustering models.
  6. Visualization & Result Dissemination 可视化与结果传播 — 把结果清楚地讲给决策者。
    Communicate findings clearly to stakeholders.
举例 Example:奶茶店预测明天销量 / A bubble-tea shop predicting tomorrow's sales:
① 收集历史销售+天气 (acquire) → ② 存数据库 (store) → ③ 清洗删掉录错的负数销量 (clean) → ④ 画图发现"周末+晴天卖得多" (EDA) → ⑤ 训练回归模型 (model) → ⑥ 给老板一张预测图 (visualize)。

2. 三种数据结构 (Three Data Structures)

Structured 结构化
有固定 schema 的关系表,行+列。
Relational tables with a fixed schema (rows & columns).
例 e.g.:SQL 表、Excel
Semi-structured 半结构化
树状嵌套、自描述、无需预定义 schema。
Nested, self-describing, no predefined schema needed.
例 e.g.:JSON、XML
Unstructured 非结构化
无固定结构。
No fixed format.
例 e.g.:文本、图片、音频、视频
高频对比 (Relational vs Semi-structured):
关系模型:每个属性必须有名字和类型、基于同质 tuple 集合、必须先定义 schema
Relational: every attribute has a name & type; based on homogeneous tuples; schema must be defined first.
JSON/XML:可树状嵌套、自描述、无 schema 也能解析
JSON/XML: tree-like nested, self-describing, can be parsed without a predefined schema.

3. Big Data 的判定 (When is it "Big Data"?)

课程定义:当数据量大到需要在多个处理节点(分布式)上处理时,才算 Big Data。
Course definition: a problem is "Big Data" when the volume is so large it must be processed on multiple nodes.

常用 3V 描述:Volume 体量、Velocity 速度、Variety 多样性。
Often described by the 3 Vs: Volume, Velocity, Variety.

❌ 错误说法 / Wrong claims:装不进内存就是大数据 (fitting in memory)、属于大公司就是大数据 (owned by a big company)、涉及隐私就是大数据 (privacy)。这些都不是课程定义。

4. 监督 vs 无监督学习 (Supervised vs Unsupervised)

Supervised 监督Unsupervised 无监督
是否需要标签 Needs labels?需要 Yes不需要 No
任务 Task分类 Classification、回归 Regression聚类 Clustering、降维 Dim. reduction
例 Example预测是否患病(有"患病/健康"标签)
predict disease (labels given)
把客户分群(无预设群)
segment customers (no preset groups)
考点 Exam point:若训练数据已知 class label既能做监督(用label)也能做无监督(忽略label)。答案常是 "either supervised or unsupervised"。
If labels are known, the data can be used for either supervised or unsupervised learning.

Week 2 · 数据类型与描述统计 (Data Types & Descriptive Statistics)

1. 四种数据类型 (4 Data Types) — 最高频 MCQ

类型 Type可排序 Order?可加减 +/−?绝对零点/可乘除 Abs.zero?例子 Example
Nominal 名义性别、颜色、Region、血型
gender, colour, blood type
Ordinal 顺序满意度1–5、学历、S/M/L、排名
satisfaction, ranking, sizes
Interval 区间✗ 无绝对零点摄氏温度、年份、IQ
Celsius, year, IQ
Ratio 比率✓ 有绝对零点重量、距离、价格、Kelvin
weight, distance, price

Nominal vs Ordinal:看有没有"顺序" / Is there an order?

颜色(红/绿/蓝)无大小 → Nominal;学历(本科<硕士<博士)有高低 → Ordinal。
Colours have no order → nominal; education levels have a rank → ordinal.

Interval vs Ratio:看有没有 absolute zero (0 是否=没有)

关键:0 这个值是否代表"完全没有这个量"。是→Ratio;只是参考点→Interval。
Key: does 0 mean "none of the quantity"? Yes → ratio; just a reference point → interval.

关键举例 Examples:
  • 摄氏 °C = Interval:0°C 不是"没有温度"(只是水冰点),所以 20°C 不是 10°C 的两倍热。
    0°C is not "no temperature", so 20°C is not twice as hot as 10°C.
  • 开尔文 Kelvin = Ratio:0K = 绝对零度(真没热能),200K 确实是 100K 的两倍。
    0K is absolute zero, so 200K really is twice 100K.
  • 年份 Year = Interval重量 kg = Ratio(0kg=没有重量)。
口诀:能说"X 是 Y 的几倍"的就是 Ratio。 / Rule: if "X is N times Y" makes sense, it's ratio.

2. 适用的描述统计 (Which statistic for which type?)

统计量 StatisticNominalOrdinalIntervalRatio
Mode 众数
Median 中位数
Mean 均值
Std/Variance 标准差/方差

逻辑:统计量需要的运算,data type 得支持才有意义。
Logic: a statistic is only meaningful if the data type supports the maths it needs.

举例 Example:5 人满意度 1,2,3,4,5 (ordinal)。算 mean=3 没意义,因为"1→2"和"4→5"的差距不一定相等。
Mean is meaningless for ordinal because gaps between ranks aren't equal.
工资 3,4,5,6,100万 (ratio,有 outlier):mean=23.6万被老板拉高,median=5万更代表典型值。
With an outlier, the median (5) represents the typical value better than the mean (23.6).
必记 Must remember:Nominal 只能 mode;Ordinal 用 mode/median,不能 mean;要算 std 必须先能算 mean → 只有 Interval/Ratio 能算 std。

3. 集中趋势 vs 离散程度 (Central Tendency vs Dispersion)

Central Tendency 集中趋势
中心在哪里 / where the centre is
Mean 均值 · Median 中位数 · Mode 众数
Dispersion 离散程度
数据多分散 / how spread out
Min · Max · Range 极差 · Variance 方差 · Std 标准差 · IQR
真题考点 Exam:哪些是 dispersion?答案 = Min, Max, Range, Variance, Std。Mode/Median/Count 不是
Range = Max − Min;IQR = Q3 − Q1 (不受 outlier 影响 / robust to outliers)。

4. 分布形状 / 偏态 (Skewness)

形状 Shape长尾在 Tail三量关系 Relation例 Example
对称 Symmetric无 nonemean ≈ median ≈ mode身高 height
右偏(正偏) Right-skewed右 rightmean > median > mode工资、房价 income, house price
左偏(负偏) Left-skewed左 leftmean < median < mode很容易的考试分数 easy-exam scores
口诀 Rule:尾巴在哪边就是哪边偏;mean 被尾巴拽走。判定:mean > median → 右偏;mean < median → 左偏。
The tail decides the skew; the mean is pulled towards the tail.

Week 5 · 数据库查询 (SQL)

1. 语句结构 & 执行顺序 (Clauses & Execution Order)

SELECT   col / agg        -- 5 选哪些列 which columns
FROM     table            -- 1 哪张表 which table
WHERE    row filter       -- 2 行过滤(聚合前,不能用聚合) filter rows
GROUP BY col              -- 3 分组 group
HAVING   group filter     -- 4 组过滤(聚合后,可用聚合) filter groups
ORDER BY col [DESC]       -- 6 排序 sort
LIMIT n                   -- 7 取前 n 行 top n

书写按上面;执行顺序 Execution order:FROM→WHERE→GROUP BY→HAVING→SELECT→ORDER BY→LIMIT。

2. 聚合函数 & GROUP BY 黄金法则

COUNT(*) 行数 · SUM 求和 · AVG 平均 · MAX/MIN 最值。

GROUP BY 黄金法则 Golden rule:SELECT 里出现的列,要么在 GROUP BY 里,要么被聚合函数包住,否则报错。
Every column in SELECT must be in GROUP BY or wrapped in an aggregate.

3. WHERE vs HAVING (高频考点)

WHEREHAVING
过滤对象 Filters行 rows (聚合前)组 groups (聚合后)
能用聚合? Aggregate?✗ 不能 No✓ 能 Yes
位置 PositionGROUP BY 之前 beforeGROUP BY 之后 after
举例 Example:找"总额>100 的客户" / customers with total > 100:
SELECT CustomerID, SUM(Amount)
FROM Orders
GROUP BY CustomerID
HAVING SUM(Amount) > 100;   -- 用 HAVING (SUM 是聚合)
❌ 不能写 WHERE SUM(Amount)>100 (WHERE 不能用聚合 / can't use aggregates)。

4. DISTINCT / JOIN / ORDER BY+LIMIT 模板 (2017 冰淇淋题)

-- a) 3月有销售的 unique 门店 / unique stores with March sales
SELECT DISTINCT store_id FROM Tx WHERE month = 3;

-- b) 3月卖出的 unique 冰淇淋名 (多表 JOIN) / multi-table join
SELECT DISTINCT i.name
FROM Tx t
JOIN Tx_IceCream ti ON t.tx_id = ti.tx_id
JOIN IceCream i      ON ti.icecream_id = i.icecream_id
WHERE t.month = 3;

-- c) 每月 total / avg / count
SELECT month, SUM(value), AVG(value), COUNT(*)
FROM Tx GROUP BY month;

-- d) 平均售价>=5 的 top-3 门店(按总销售降序)
SELECT store_id, SUM(value) AS total
FROM Tx
GROUP BY store_id
HAVING AVG(value) >= 5
ORDER BY total DESC
LIMIT 3;

5. 日期/时间运算 (Date/Time arithmetic, 24S1真题)

SELECT event_timestamp + INTERVAL '36 hours' AS new_ts,
       event_date      + INTERVAL '1 day'    AS new_date
FROM EventSchedule;

Week 8 · 聚类与降维 (Clustering & Dimensionality Reduction)

1. K-means 聚类 (必考)

  • 输入需指定 k(簇数),算法不会自动算 k。
    k (number of clusters) must be given as input; not computed automatically.
  • 每个点分到最近 centroid(质心)的簇。
    Each point goes to the nearest centroid.
  • 目标:最小化簇内方差 / SSE
    Objective: minimise within-cluster variance / SSE.
  • 迭代 Steps:① 初始化 k 个 centroid → ② 每点归最近 centroid → ③ 重算 centroid(均值) → ④ 重复至收敛。
❌ 错误:k-means 是层次聚类 / 自动算 k / 只能 nominal。✓ 正确:以 k 为输入、最小化簇内方差、归最近 centroid;用距离故需数值数据 (numeric)。

2. 层次聚类 (Hierarchical / Agglomerative)

步骤顺序 (真题排序题) / Step order

  1. 每个点自成一簇 / each point its own cluster
  2. 找最近的一对簇 / find the closest pair
  3. 合并成一个簇 / merge into one
  4. 重算新簇与其他簇距离 / recompute distances
  5. 重复 2–4 直到只剩一簇 / repeat until one cluster
方法 Linkage定义 Definition
Single-link 单连接两簇间最近点对距离 / closest pair
Complete-link 全连接两簇间最远点对距离 / farthest pair
Average-link 平均连接所有点对距离平均 / average of all pairs
Single-link 举例 (Sample Q7 城市距离):找最小距离先合并。BOS-NY=206 最小 → 先合 {BOS,NY};再 SF-LA=379 → 合 {SF,LA};再把 DC 并入 {BOS,NY}…依距离从小到大。

3. Silhouette 系数 (聚类质量)

s = (b − a) / max(a, b) a = 该点到本簇其他点的平均距离 (avg dist within own cluster) b = 该点到最近邻簇点的平均距离 (avg dist to nearest other cluster)
  • s ≈ 1:分得好(贴合本簇) / well matched。
  • s ≈ 0:在两簇边界 / on the boundary。
  • s < 0:可能分错簇 / possibly misassigned。
  • s ∈ [−1, 1],不会 >1。

4. 如何选 k (Choosing k)

  • Silhouette:越高越好(选峰值) / higher is better, pick the peak。
  • SSE 肘部法 Elbow:SSE 随 k 单调下降,不能只选最小;找"下降突然变缓"的肘部。
    SSE decreases monotonically with k; pick the elbow, not the minimum.
2017真题:silhouette k=2/3/4/5=0.75/0.84/0.67/0.48,SSE=4484/491/434/379。
k=3:silhouette 最高;SSE 从 2→3 暴跌(4484→491),之后趋缓(肘部在 3)。

5. 降维 PCA (Dimensionality Reduction)

把高维数据投影到少数主成分(principal components),保留最大方差方向,去冗余。用途:可视化、加速、降噪、缓解维度灾难。
Project to few principal components keeping max variance; for visualisation, speed, denoising.

Week 9 · 线性回归与逻辑回归 (Linear & Logistic Regression)

1. 简单线性回归 (Simple Linear Regression)

  • 在因变量 Y 与一个自变量 X 之间找最佳拟合直线
    Finds the line of best fit between Y and ONE independent variable X.
  • 模型 Y = α + βX,学 α 截距(交 y 轴) 和 β 斜率
    Learns intercept α and slope β.
  • 多个自变量 → multiple linear regression 多元
❌ 错误:simple regression 用任意多个自变量(那是 multiple)、包含参数 rho、与相关性提供完全相同信息。

2. 回归评估 (Evaluation)

  • Residual/Error 残差 = y_true − y_predicted。
  • SSE/MSE/RMSE:误差平方度量,越小越好 / lower is better。
  • = 解释方差/总方差 ∈[0,1],越接近 1 越好。
    R² = explained variance / total variance; closer to 1 is better.
  • 残差图 Residual plot:点随机散在 0 附近=好;呈曲线形状=非线性、拟合差。

3. 逻辑回归 (Logistic Regression)

  • 用于分类(非连续预测);输出概率 0–1,用 sigmoid
    Used for classification; outputs a probability via sigmoid.
  • 概率 > 阈值(默认0.5) → 判正类。
  • cost function 必须可微 differentiable,才能用梯度下降 gradient descent(24S1真题)。
  • 降低 false negative(漏报)调低阈值,重视 recall。
    To reduce false negatives, lower the threshold / favour recall.
举例:Stephen 做睡眠障碍诊断,想"少漏诊" → 调低阈值提高 recall,评估重点看 recall 而非 accuracy。

Week 10 · 决策树 (Decision Tree)

1. 核心概念 (Core idea)

按所选属性递归划分样本,直到节点纯净或无属性可分;叶节点给预测类别。
Recursively partition samples by the chosen attribute until pure; leaves give the predicted class.

2. 熵与信息增益 (Entropy & Information Gain)

Entropy(S) = −Σ pᵢ · log₂(pᵢ) 纯节点(全同类) Pure node → Entropy = 0 50%/50% → Entropy = 1 (最不确定 most uncertain) Information Gain = Entropy(父 parent) − Σ (子占比 × Entropy(子 child)) = 父熵 − 加权条件熵 (weighted child entropy)

选 Information Gain 最大 ⇔ 条件熵最小 的属性来划分。
Pick the attribute with the highest information gain = lowest weighted child entropy.

举例 (Sample Q8):节点 15正15负(父熵=1),三划分条件熵 A=0.40,B=0.60,C=0.80。Gain_A=1−0.40=0.60(最大) → 选 Split A。条件熵越小,Gain 越大。
❌ 高频错误:"higher entropy 表示最佳划分属性"——错!应是 higher information gain / 更低条件熵

3. 建树举例 (2017 buys_computer)

Gain(age)=0.246, Gain(student)=0.151, Gain(credit)=0.048, Gain(income)=0.029。
根节点选 Gain 最大 = age(0.246),按 ≤30 / 31–40 / >40 分三支。31–40 全 true → 叶节点 yes。≤30 和 >40 分支再选剩余属性 Gain 最大者递归。

4. 过拟合与优缺点 (Overfitting / Pros & Cons)

  • 太深 → 过拟合(学噪声);用剪枝 pruning或限深缓解。
  • 优点 Pros:可解释性强、不需特征缩放、能处理类别特征。缺点 Cons:易过拟合、不稳定。
  • Random Forest = 多棵树投票,降低过拟合 / ensemble of trees to reduce overfitting。

Week 12 · 数据伦理 (Data Ethics)

核心立场 (Key Positions) — 真题多为多选/判断

  • 数据科学不是价值中立的活动。
    Data science is NOT an ethically neutral activity.
  • 模型既预测未来,也影响未来;数据科学家有责任沟通并减轻可能的危害
    Models both predict AND affect the future; the data scientist must communicate and mitigate harm.
  • 历史数据训练 → 会把制度性偏见(institutional bias)带进模型。
    Historical data exposes the model to institutional bias present when it was collected.
  • 即使敏感特征(如 gender)是强预测变量,使用它也可能延续/放大偏见,应慎用或不用。
    Even a strong predictor like gender may perpetuate bias and should be used with caution.
  • 机器学习从数据偏见中学习——"数学不会撒谎"是错误说法。
    ML DOES learn bias from data; "maths doesn't lie" is wrong.
举例 (2017真题):预测学生能否完成学业,历史数据含 gender。即使 gender 强预测也不该用——会延续历史偏见(perpetuate bias)。
关键词 Keywords (简答可用):fairness 公平、bias 偏见、transparency 透明、accountability 问责、privacy 隐私、harm mitigation 危害减轻、informed consent 知情同意。
Q2 · 数据清洗 + EDA(15分大题)

Week 4 · ETL 与数据清洗 (ETL & Data Cleaning)

1. ETL 三步 (Extract → Transform → Load)

  • Extract 抽取:从 CSV/API/网页/数据库读原始数据。
    Read raw data from CSV/API/web/database.
  • Transform 转换:清洗+改格式(去重、补缺、单位统一、合并)。数据清洗在这一步
    Clean & reshape; data cleaning happens here.
  • Load 加载:写入目标数据库(如 PostgreSQL)。
    Write into the target database.

2. 清洗包含 / 不包含什么 (真题考点)

✓ 属于 cleansing
纠错(城市↔邮编)、outlier 移除、'n/a'→NULL、删不完整记录、harmonization('one'→1)、单位统一
correcting errors, outlier removal, n/a→NULL, removing incomplete rows, harmonisation, unit conversion
✗ 不属于 cleansing
Data anonymization 匿名化(那是隐私保护,不是清洗)
Anonymisation is privacy protection, NOT cleansing.

3. 七大数据质量问题 (7 Data Quality Issues) — Sample Q2 大题必考

#类型 Issue (术语)长什么样 Looks like清洗 Cleaning
1Missing value 缺失值"missing"/"unknown"/空/NaN替换 NaN,数值→median,类别→mode
2Duplicate 重复整行出现两次 (D009)drop_duplicates()
3Invalid value 无效值PackageWeight=-1.2 (负重量)→NaN 再 median 填
4Out-of-range 超范围Rating=6 但范围1–5→NaN,删或 mode 填
5Inconsistent format 格式不一2024-04-01 vs 01/04/2024统一成 YYYY-MM-DD
6Inconsistent labels 标签不一Metro/metro/REG/Regional转小写+字典映射统一
7Outlier 异常值DeliveryTime=999, Weight=30先调查真伪,再删/保留
答题三段式 (3-part format for full marks):
Issue: Row X, column Y is [value] → this is a [issue type 术语].
Why: It is a problem because [影响:让统计/模型出错 distorts stats/model].
Cleaning: [方法 method], because [理由 reason: median is robust to outliers / rating is ordinal so use mode].
范例 Sample answer:
Issue: In row D005, PackageWeight is the text "missing" — a missing value encoded as text.
Why: Python won't treat it as NaN, so numeric operations (mean/std) will fail.
Cleaning: Replace "missing" with NaN, then impute with the median, because the median is robust to outliers.

4. 关系型数据库好处 (Benefits of RDBMS) + 键 (Keys)

  • Declarative querying 声明式查询:只说"要什么结果",不写"怎么算"(SQL)。
    Specify WHAT result you want, not HOW to compute it.
  • Schema + 约束保证数据一致性 integrity;减少冗余 redundancy。

PK vs FK:Primary Key 主键 唯一标识本表一行(如 CustomerID);Foreign Key 外键 在另一张表引用该 PK,用来 JOIN。
Primary key uniquely identifies a row; foreign key references another table's PK to join.

Week 3 · 探索性数据分析与可视化 (EDA & Visualization)

1. EDA 是什么、为什么 (What & Why)

EDA = 建模前"先看一眼数据"。目的:① 了解分布 distribution;② 找变量间关系 relationships;③ 发现异常 anomalies (outlier/missing/错误)。
EDA = look at the data before modelling: understand distribution, find relationships, detect anomalies.

分析层级 Levels

  • Univariate 单变量:只看一列 / one variable (e.g. DeliveryTime 的分布)。
  • Bivariate 双变量:两列关系 / two variables (e.g. Distance vs Time)。
  • Multivariate 多变量:3+ 列一起 / 3+ variables (e.g. heatmap)。

2. 选图速查 (Choosing the right chart)

想回答的问题 Question用什么图 Chart例 Example
一个数值变量怎么分布? / distribution of one numeric varHistogram 直方图 / Boxplot 箱线图包裹重量大多几 kg?
一个类别变量哪类多? / counts of one categoricalBar chart 柱状图各 Region 配送数量
数值 vs 数值有关系吗? / relationship num–numScatter plot 散点图距离越远时间越长?
类别 vs 数值对比? / categorical vs numericGrouped Boxplot 分组箱线图各 Region 的配送时间
类别 vs 类别? / cat vs catStacked bar / CrosstabRegion vs 是否延误
异常值? / find outliersBoxplot (盒外的点)DeliveryTime 有无 outlier
数值变量相关性? / correlationsCorrelation heatmap 热力图重量/距离/时间相关性
最易混 Most confused:看"分布"用 Histogram(一个变量);看"关系/A越…B越…"用 Scatter plot(两个变量)。
Distribution → Histogram (1 var); relationship → Scatter plot (2 vars).

3. 坏图诊断 (What's wrong with this chart?) — 真题简答

2017真题:对 5 种口味的 1–5 评分(ranking)画"Sum of Rankings vs Flavour",问哪里错?
答:评分是 ordinal 数据,对 ranking 求和(sum)没有统计意义(间距不等);应展示分布/median/mode。
Ratings are ordinal; summing rankings is meaningless because gaps aren't equal. Use distribution / median / mode instead.

其他坏图毛病 / Other issues:缺坐标轴标签或单位 (missing axis labels)、Y 轴不从 0 开始造成误导 (truncated y-axis)、用饼图比较太多类别、把 ordinal 当 interval 平均。

Q3 · 关联规则挖掘(15分大题)

Week 7 · 关联规则挖掘 (Association Rule Mining)

1. 三个核心度量 (Support, Confidence, Lift)

对规则 X → Y,设 N = 总交易数 / N = total transactions:

Support(X→Y) = count(X∪Y) / N ← X、Y 同时出现的比例 (how common) Confidence(X→Y) = count(X∪Y) / count(X) ← 买X的人里多少也买Y (reliability) Lift(X→Y) = Confidence(X→Y) / Support(Y) = support(X∪Y) / (support(X)·support(Y))
  • Support 高 = 组合常见,值得关注 / common & worth attention。
  • Confidence 高 = X 出现时 Y 很可能出现 / rule is reliable。
  • Lift > 1 正相关 positive;=1 独立 independent;< 1 负相关 negative。

2. 完整计算举例 (Worked example, Sample Q3, N=1200)

已知 Drama=600, Comedy=480, Drama∧Comedy=300。
Rule1 {Drama}→{Comedy}:
Support = 300/1200 = 0.25
Confidence = 300/600 = 0.50 (买Drama的人50%也买Comedy)
Lift = 0.50 / (480/1200) = 0.50/0.40 = 1.25 > 1 → 正相关,看Drama提升看Comedy概率25%
Lift 1.25 > 1 → positive: watching Drama raises the chance of Comedy by 25%.

Rule2 {Comedy}→{Drama}: Confidence = 300/480 ≈ 0.625 > 0.50 → 方向不对称 (asymmetric)。
易错 (24S1):support 与 confidence 相互独立——可高confidence低support、可低confidence高support、也可都低。
Support and confidence are independent; any combination is possible.

3. 手算 (Hand calculation, 2017 冰淇淋)

5笔交易,含 Chocolate 3笔、含 Sprinkles 4笔、同时含 2笔,N=5。
Chocolate→Sprinkles:Support=2/5=40%,Confidence=2/3≈66%
Sprinkles→Chocolate:Support=2/5=40%,Confidence=2/4=50%
(support 对称 symmetric,confidence 不对称 asymmetric)
Q4 · 朴素贝叶斯(15分大题)

Week 11 · 非结构化数据与朴素贝叶斯 (Naive Bayes)

1. 贝叶斯定理与朴素假设 (Bayes + Naive Assumption)

P(class | x) ∝ P(class) · Π P(xᵢ | class) "朴素 Naive" = 假设各特征在给定类别下条件独立,故概率可相乘。 Naive = features are conditionally independent given the class.
变体 Variant适用特征 Features例 Example
Categorical/Multinomial离散类别 categoricalHead/Eyes/Size、词频
Gaussian连续数值 continuous身高体重(假设正态)
Bernoulli二值 binary 0/1词是否出现

2. 分类步骤 + 完整举例 (Steps + Worked Example, Sample Q4)

数据 9 行,分类 Head=Triangle, Eyes=Round, Size=Large:
① 选变体 Variant:特征都是类别 → Categorical NB。
② 先验 Priors:P(Yes)=4/9, P(No)=5/9。
③ 条件概率 Conditionals:(Yes类:行1,5,6,9; No类:行2,3,4,7,8)
P(Triangle|Yes)=3/4, P(Round|Yes)=1/4, P(Large|Yes)=1/4
P(Triangle|No)=0/5, P(Round|No)=3/5, P(Large|No)=3/5
④ 相乘比较 Multiply & compare:
Yes ∝ (4/9)×(3/4)(1/4)(1/4) ≈ 0.0208
No ∝ (5/9)×0×… = 0 ← 出现 0 概率 (zero probability)
→ 不平滑判 Yes;规范用 Laplace 平滑(每计数+1)避免 0,再比较。
0 概率问题 Zero-probability:某条件训练集没出现 → 概率=0 让整个乘积归零。解决:Laplace(加一)平滑。考试写出这点能加分。
优势举例(24S1):待分类组合(Red Domestic SUV)训练集没出现过,但 NB 靠各特征独立相乘仍能分类。
Q5 · 模型对比 + 评估(15分大题)

Week 6 · 假设检验与模型评估 (Hypothesis Testing & Evaluation)

1. 假设检验基础 (Hypothesis Testing)

  • Research Question 研究问题:问自变量是否有影响
    Asks whether an independent variable has an effect.
  • Null Hypothesis H₀ 零假设:假设没有影响
    Assumes there is no effect.
  • p-value:在 H₀ 为真的前提下,观察到当前或更极端数据的概率。
    Probability of observing data this extreme if H₀ were true.
  • 决策:p < 0.05 → 拒绝 H₀p 越小,反对 H₀ 证据越强
    p < 0.05 → reject H₀; the smaller p, the stronger the evidence against H₀.
举例 Example:研究"新药是否降血压" H₀=无效。得 p=0.01 < 0.05 → 拒绝 H₀,认为药有效。p=0.08 → 不能拒绝。
严格小于:p=0.05 不能在 0.05 水平拒绝;p=0.01 可以。
Strictly less-than: p=0.05 cannot be rejected at 0.05; p=0.01 can.

两类错误 (Type I / II error)

H₀ 实际为真 H₀ trueH₀ 实际为假 H₀ false
拒绝 H₀ RejectType I error 假阳性 (P=α)✓ 正确 correct
不拒绝 H₀ Don't reject✓ 正确 correctType II error 假阴性
记忆 Memory:Type I = 拒真(冤枉好人/误报 false positive);Type II = 纳伪(放走坏人/漏报 false negative)。
❌ "p<0.05 表示 H₀ 为真的概率是 95%" 是错误说法。

2. 相关性检验 (Correlation)

  • Pearson:测线性关系,适合正态/连续。
    Measures linear relationship; for normal/continuous data.
  • Spearman:测单调关系,适合非正态/ordinal/有异常值。
    Measures monotonic relationship; for non-normal/ordinal data.

r ∈ [−1,1],接近 ±1 强相关,接近 0 无线性相关。相关 ≠ 因果 / correlation ≠ causation。

3. Train / Development / Test 划分

  • Training set 训练集:训练模型;用 cross-validation 交叉验证 做调参。
    Train models; use cross-validation for tuning.
  • Development/Validation set 验证集:评估调参,但节制使用防过拟合。
    Evaluate tuning, but use sparingly to avoid overfitting.
  • Held-out Test set 测试集只用一次做最终评估;绝不放进训练,也不反复调参。
    Use only ONCE for final evaluation; never include in training.

4. 过拟合 vs 欠拟合 (Overfitting vs Underfitting)

Overfitting 过拟合Underfitting 欠拟合
训练集 Train很好 good差 poor
测试集 Test差(泛化差) poor差 poor
原因 Cause学到噪声、太复杂、high variance太简单、high bias
举例:Sample Q5 决策树 train acc=0.97 但 test acc=0.73 → 典型过拟合。高方差模型更易过拟合;增加数据/剪枝可缓解。
Train 0.97 vs test 0.73 = classic overfitting; more data or pruning helps.

5. 分类评估:混淆矩阵 (Confusion Matrix)

Predicted YesPredicted No
Actual YesTP 真阳FN 假阴/漏报
Actual NoFP 假阳/误报TN 真阴
Precision = TP / (TP + FP) ← 预测为正中真正是正的比例 (of predicted positives, how many right) Recall = TP / (TP + FN) ← 真实正例中被抓到的比例 (of actual positives, how many caught) F1 = 2·P·R / (P + R) ← P 和 R 的调和平均 (harmonic mean) Accuracy = (TP + TN) / 全部 all
计算举例 (Sample Q5):TP=36, FN=24, FP=46, TN=294
Precision = 36/(36+46) = 36/82 ≈ 0.44
Recall = 36/(36+24) = 36/60 = 0.60
F1 = 2×0.44×0.60 / (0.44+0.60) ≈ 0.51
"最高 test acc/F1 ≠ 最该部署"理由 (why highest acc/F1 isn't enough):
① 类别不平衡时 accuracy 误导 (imbalanced → accuracy misleads);② 漏诊(FN)成本未体现,医疗需高 recall (cost of FN);③ 可解释性/部署成本/速度 (interpretability/cost);④ 单一测试集偶然性,需交叉验证 (single test set);⑤ 公平性与伦理 (fairness)。
不平衡举例:罕见病占1%,全猜"健康"也有99% accuracy 但 recall=0 → 必须看 recall/F1。

6. 模型横向对比 (Model Comparison) — Q5 必备

Q5 是 model comparison and evaluation,除了算指标,还要能横向比较不同模型的假设、优劣、适用场景。

模型 Model假设 Assumption优点 Pros缺点 Cons适用 When
Logistic 回归线性决策边界,输出概率可解释(系数/概率)、快只能线性边界、需特征缩放、欠拟非线性要可解释的二分类
决策树 Decision Tree无分布假设,按信息增益贪心分裂可解释(if-then规则)、处理非线性&类别、无需缩放易过拟合、不稳定(数据小变树大变)要规则可读
随机森林 Random Forest多棵树投票(bagging)准确率高、抗过拟合、稳健可解释性差(黑盒)、计算重要高准确率
朴素贝叶斯 Naive Bayes给定类别下特征条件独立极快、小数据好、天然多类、缺见组合仍可分独立假设常不成立、0概率需 Laplace文本/高维类别
kNN近邻相似,惰性(无训练)简单、非线性、无需训练预测慢、需缩放、维度灾难、对k敏感小数据低维
怎样公平比较 (how to compare fairly):相同的 train/test 划分 + 相同指标(F1/AUC) + k-fold 交叉验证取平均,不要只看 accuracy(不平衡会误导)。
选哪个的 justify 句式:"I would use X because the data is/goal is ___"——要可解释→logistic/tree;要非线性&类别→tree/forest;高维/文本→NB;类别不平衡→看 F1 而非 accuracy;小数据→NB/kNN。
速查 · Cheat Sheet

📋 考前高频考点速查 (Cheat Sheet)

  • 数据类型↔统计量 Data type ↔ stats:Nominal只mode,Ordinal加median但不能mean
  • Interval vs Ratio:绝对零点 absolute zero (Kelvin=Ratio, 摄氏/年份=Interval)
  • Dispersion:Min/Max/Range/Var/Std (Mode/Median/Count不是)
  • 选图 Charts:分布→Histogram,关系→Scatter;坏图→对ordinal求和无意义
  • 清洗 Cleaning:7问题 + 三段式答题;匿名化不算清洗
  • SQL:GROUP BY黄金法则、WHERE(行/不能聚合) vs HAVING(组/可聚合)、DISTINCT、JOIN、ORDER BY+LIMIT
  • 假设检验 Hypothesis:H₀=无影响,p小=证据强,p<0.05拒绝;Type I=拒真,Type II=纳伪
  • 评估 Eval:Precision=TP/(TP+FP), Recall=TP/(TP+FN), F1=2PR/(P+R);过拟合=train高test低
  • 关联规则 Rules:Support=共现/N, Confidence=共现/X, Lift=Conf/Support(Y);lift>1正相关
  • 聚类 Clustering:k-means需给k+最小化簇内方差;single-link=最近点对;silhouette≈1好;选k看silhouette峰值+SSE肘部
  • 回归 Regression:线性学α/β、R²;逻辑回归分类、cost可微、降FN调低阈值
  • 决策树 Tree:Entropy=−Σplog₂p,选Gain最大(条件熵最小);age例root
  • 朴素贝叶斯 NB:先验×条件概率连乘;0概率用Laplace平滑
  • 伦理 Ethics:非中立、模型影响未来、历史数据带偏见、慎用敏感特征
已答 0 / 0 正确 0 错误 0 得分率
📌 使用说明:本测试按真实考试结构组织——Q1 选择题(25题/40分) + Q2–Q5 四道大题(各15分)。选择题点选即判分、显示解析。大题 问答 先自己写答案,再点"参考答案"对照;如需我批改,直接截图发给我即可。
🎯 今年大题主题(已确认):Q2 数据清洗+EDA|Q3 关联规则|Q4 朴素贝叶斯|Q5 模型对比+评估。SQL/聚类/决策树/回归主要出现在 Q1 选择题。
Q1 · 选择题 MCQ(25题/40分,点选即判分)
Q2–Q5 · 大题(各15分,按主题分组;自答后看参考答案,或截图问我)