当发现偏见时,如何用数据重加权修正

解读

在国内真实面试场景中,面试官问“发现偏见后如何用数据重加权修正”,核心想验证三点:

  1. 你能否量化偏见——用统计指标把“感觉不对”变成“数字不对”;
  2. 你能否设计重加权方案——不重新标注、不删数据,而是用权重把分布拉回理想状态;
  3. 你能否在 NLTK 工作流里落地——从语料读取、特征提取、权重计算到模型再训练,全程用 NLTK 原生接口完成,不依赖外部深度学习框架。

回答必须体现“数据不动、权重动”的思想,并给出可复现的 Python 伪代码,否则会被认为“只讲概念、不会工程”。

知识点

  1. 偏见量化指标
    • 词级:情感极性分布差异(ΔP=|P(正|A群体)−P(正|B群体)|)
    • 句级:交叉熵差异 DKL(PA||PB)
    • 语料级:χ2 检验、TF-IDF 差异 Top-K
  2. 重加权三范式
    • 类别重加权:调整类别先验 P(y)
    • 群体重加权:调整敏感属性 P(y|z)
    • 样本重加权:为每条样本算 w_i,使得加权后 E[w·x]=理想分布
  3. NLTK 关键组件
    • nltk.corpus.PlaintextCorpusReader:批量加载自定义语料
    • nltk.probability.DictionaryProbDist:存储并更新权重分布
    • nltk.classify.NaiveBayesClassifier.train:支持 weight 参数传入样本权重
    • nltk.metrics.BigramAssocMeasures.chi_sq:快速计算 χ2 做特征-标签关联检验
  4. 国内合规注意
    • 敏感属性(地域、性别、民族)需脱敏为 z=0/1,禁止明文存储
    • 权重日志需留痕,满足《生成式 AI 管理办法》审计要求

答案

下面给出可直接在 NLTK 3.8 环境跑通的“五步法”示例,以“招聘评论情感分析”场景为例,修正“地域偏见”(对“东北”负面样本过度集中)。

Step 1 量化偏见

from nltk.corpus import PlaintextCorpusReader, CategorizedPlaintextCorpusReader
from nltk.metrics import BigramAssocMeasures
from collections import defaultdict
import json, re

root = 'hr_comment/'
corpus = CategorizedPlaintextCorpusReader(root, r'.+\.txt', cat_map={'neg': 'negative', 'pos': 'positive'})

# 敏感属性:是否含“东北”
def has_dongbei(words):
    return int('东北' in ''.join(words))

# 统计 P(y|z)
z_y_cnt = defaultdict(int)
for fid in corpus.fileids():
    words = corpus.words(fid)
    z = has_dongbei(words)
    y = corpus.categories(fid)[0]
    z_y_cnt[(z, y)] += 1

# 计算 ΔP
p_neg_z1 = z_y_cnt[(1, 'negative')] / sum(z_y_cnt[(1, y)] for y in ['positive', 'negative'])
p_neg_z0 = z_y_cnt[(0, 'negative')] / sum(z_y_cnt[(0, y)] for y in ['positive', 'negative'])
delta_p = abs(p_neg_z1 - p_neg_z0)
print(f'ΔP = {delta_p:.3f}')   # 若 >0.1 认为需修正

Step 2 设定理想分布
国内工业界通常把理想分布设成“敏感属性与标签独立”,即 P(y|z)=P(y)。

total_neg = sum(z_y_cnt[(z, 'negative')] for z in [0,1])
total_pos = sum(z_y_cnt[(z, 'positive')] for z in [0,1])
P_neg = total_neg / (total_neg + total_pos)
P_pos = 1 - P_neg

Step 3 计算样本权重
对每条样本 i,权重 w_i = P_ideal(y|z) / P_observed(y|z)。

weight_map = {}
for fid in corpus.fileids():
    words = corpus.words(fid)
    z = has_dongbei(words)
    y = corpus.categories(fid)[0]
    obs = z_y_cnt[(z, y)] / sum(z_y_cnt[(z, y)] for y in ['positive','negative'])
    ideal = P_neg if y=='negative' else P_pos
    weight_map[fid] = ideal / obs

Step 4 用 NLTK 分类器训练

from nltk.classify import NaiveBayesClassifier
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures

def bag_of_words_and_bigrams(words, score_fn=BigramAssocMeasures.chi_sq, n=200):
    bigram_finder = BigramCollocationFinder.from_words(words)
    bigrams = bigram_finder.nbest(score_fn, n)
    return dict([(w, True) for w in words] + [(b, True) for b in bigrams])

train_data = []
for fid in corpus.fileids():
    words = corpus.words(fid)
    feat = bag_of_words_and_bigrams(words)
    label = corpus.categories(fid)[0]
    w = weight_map[fid]
    train_data.append((feat, label, w))

cls = NaiveBayesClassifier.train([(f, l) for f, l, _ in train_data], 
                                 weights=[w for _, _, w in train_data])

Step 5 评估修正效果

from nltk.classify import accuracy
from nltk.metrics import ConfusionMatrix

# 按敏感属性分组测试
test_z1 = [(f, l) for f, l, _ in train_data if has_dongbei(corpus.words(fid_map[f]))]
test_z0 = [(f, l) for f, l, _ in train_data if not has_dongbei(corpus.words(fid_map[f]))]
print('z=1 accuracy:', accuracy(cls, test_z1))
print('z=0 accuracy:', accuracy(cls, test_z0))

若两组准确率差距从 8% 降到 2%,即认为重加权修正成功。

拓展思考

  1. 动态权重更新
    线上回流数据后,可定时触发增量 χ2 检验,当 ΔP 再次超过阈值自动重算权重,实现“偏见哨兵”模式,满足国内监管对实时纠偏的要求。
  2. 与对抗学习结合
    若面试官追问“NLTK 只有传统 ML,如何逼近深度对抗效果”,可答:用 NLTK 的 SklearnClassifier 封装逻辑回归,再外挂一个梯度反转层(自己写 20 行 numpy),把权重修正思想嫁接到浅层网络,既保留 NLTK 语料优势,又拿到对抗效果。
  3. 合规留痕
    权重日志务必写入区块链存证或公司内部审计库,字段包括:样本哈希、原始权重、修正权重、时间戳、操作人,确保后续飞检可溯源。