注意:根据 OP 添加的新信息,现在不推荐使用此答案。该答案与上下文相关,因此未删除。
如果单词同时出现在两个字典中,您可以对比例相等进行 z 检验。
这个过程有两个步骤——Python和统计的组合:
- 有效地创建常用词的字典,计算它们在每个样本中的相对计数。
- 计算两个样本的比例测试,同样有效地用于整个通用词典。
高效创建常用词典
计算比例的一种有效方法(注意所有代码都是 Python 3.3)是使用字典推导:
import math as math
import scipy.stats as sps
from collections import defaultdict
dictA = {'word1': 1, 'word2': 4, 'word7': 99, 'word13': 17}
dictB = {'word71': 1, 'word3': 4, 'word2': 99, 'word7': 17, 'word9': 45}
# compute the sums of the frequencies of occurrence of all the words
# NOTE this is expensive, but is done only once
sumValuesA = sum(dictA.values())
sumValuesB = sum(dictB.values())
dictAB = {key: (value, dictB.get(key)) for key,
value in dictA.items() if key in dictB.keys()}
print(dictAB)
现在您有了一个字典,其中包含任一字典中单词的计数。您可以使用 形成您选择的比例测试dictAB
。
比较样本之间的比例
可以根据给定次数的试验中的成功比例来检验两个给定样本的成功概率是否在统计上相等。
为了清楚起见,在下文中,样本是包含单词的两个文档,试验是任一文档中的单词总数,成功是任一文档中特定单词的总数。
即其中是总体 1 的成功概率,是样本 2 的成功概率。H0:p1=p2p1p2
检验统计量为
Z=p^1−p^2p^(1−p^)(1N1+1N2)−−−−−−−−−−−−−−−−√
其中和是第 j 个群体中的成功次数是个群体中的试验次数人口,和。p^j=XjNj,j=1,2XjjNjjp^=X1+X2N1+N2
在原假设下,该统计量是标准正态分布的。这是执行此操作的 Python 代码:
#================================================
# compute the two sample difference of proportions
#================================================
def fnDiffProp(x1, x2, n1, n2):
'''
inputs:
x1: the number of successes in the first sample
x2: the number of successes in the second sample
n1: the total number of 'trials' in the first sample
n2: the total number of 'trials' in the second sample
output:
the test statistic, and the p-value as a tuple
'''
hatP = (x1 + x2)/(n1 + n2)
hatQ = 1 - hatP
hatP1 = x1/n1
hatP2 = x1/n2
Z = (hatP1 - hatP2)/(math.sqrt(hatP*hatQ*(1/n1 + 1/n2)))
pVal = 2*(1 - sps.norm.cdf(Z))
return((Z, pVal))
# apply the function above to each of the common words across the
# two samples
dictPropTest = {key: fnDiffProp(value[0], value[1],
sumValuesA, sumValuesB) for key, value in dictAB.items() }
例如,“word7”的比例差异在文档中非常显着,而“word2”则不然。