Bootstrap t方法的Python实现
我有这个函数来执行,样本和总体使用字典中的同一个键。正如预期的那样,它工作得很好Bootstrap t方法的Python实现,python,python-3.x,numpy,statistics,Python,Python 3.x,Numpy,Statistics,我有这个函数来执行,样本和总体使用字典中的同一个键。正如预期的那样,它工作得很好 def ttest_(d): result = {} for k, (l, t) in d.items(): mean_sample = np.mean(t) mean_population = np.mean(l) sd_sample = np.std(t, ddof=1) sd_population = np.std(l, ddo
def ttest_(d):
result = {}
for k, (l, t) in d.items():
mean_sample = np.mean(t)
mean_population = np.mean(l)
sd_sample = np.std(t, ddof=1)
sd_population = np.std(l, ddof=1)
sample_size = len(t)
population_size = len(l)
result[k] = round(((mean_sample - mean_population) /
np.sqrt(((sd_sample/np.sqrt(sample_size))**2) +
((sd_population/np.sqrt(population_size))**2))), 2)
如何修改此函数以实现:
-->不要只进行一次最终计算,而是在引导过程中进行x次,如下所示:
for _ in range(1000)
-->上一步,将创建每个键的T-测试分布,然后结果[k]将是第n个百分位值。。。。可以使用参数指定,并给出一个值,例如0.05
编辑#1:
为清楚起见,我使用该功能的方式如下:
pairs = {}
for (k, v), (k2, v2) in product(population.items(), samples.items()):
if k == k2:
pairs.update({k: (v, v2)})
然后将公式应用于本条:
ttest_ = ttest_(pairs)
编辑#2:
重要的是要保留在字典字典上应用函数的这种结构,以便在不同的样本和键之间建立关联,并获得关联的结果[k]。唯一的区别是添加引导和百分位选择
编辑#3:
多亏了诺曼的问题。为了澄清这一点,在新公式中,将同一样本[k]与从总体[k]中抽取的随机子样本进行x次比较,这就是得到分布的方式。这些子样本的大小与原始样本[k]相同 如果我理解正确的话,这应该可以
from itertools import product
import numpy as np
# Generate fake data.
keys = np.arange(100, 130)
populations = {}
samples = {}
for k in keys:
loc = np.random.uniform(-9.0, +9.0)
scale = np.random.uniform(0.4, 4.0)
n = np.random.randint(400, 800)
m = np.random.randint(20, 100)
populations[k] = np.random.normal(loc, scale, n)
samples[k] = np.random.choice(populations[k], m, replace=False)
print('data: key={} pop={} samp={}'.format(k, len(populations[k]), len(samples[k])))
def ttest_(d, p, n=1000):
result = {}
percentiles = (np.arange(n) + 0.5) / n
for k, (pop, sample) in d.items():
size_sample = len(sample)
mean_sample = np.mean(sample)
sd_sample = np.std(sample, ddof=1)
# Generate a distribution of t values.
tvalues = np.zeros(n)
for i in range(n):
sample2 = np.random.choice(pop, size=size_sample, replace=True)
size_sample2 = len(sample2)
mean_sample2 = np.mean(sample2)
sd_sample2 = np.std(sample2, ddof=1)
# Welch's t-test for sample and sample2.
tvalues[i] = (mean_sample - mean_sample2) / \
np.sqrt((sd_sample / np.sqrt(size_sample))**2 +
(sd_sample2 / np.sqrt(size_sample2))**2)
# Interpolate the quantile function at p.
tvalues.sort()
result[k] = round(np.interp(p, percentiles, tvalues), 2)
return result
pairs = {}
for (k, v), (k2, v2) in product(populations.items(), samples.items()):
if k == k2:
pairs[k] = (v, v2)
result = ttest_(pairs, p=0.5)
for k, v in result.items():
print('result: key={} t={}'.format(k, v))
我无法改变“从可靠来源寻找答案”的说法……我不一定希望这样。只是一个很好的答案。ThanksHow“为每个键创建t测试分布”?引导会做什么x次?它应该从样本中随机抽取子样本,然后计算它们的t值吗?@Norman,这样样本总是相同的(每个键),并且与从总体中抽取的子样本进行x次比较,得到x个不同的t值。