生成置换样本
在视频中,您了解到置换抽样是用来模拟"两组变量具有相同概率分布"这一原假设的有力方法。这个假设在实际分析中经常需要检验。本练习中,您将编写一个函数,从两个数据集生成一组置换样本。
回顾一下:对于包含 n1 和 n2 个元素的两个数组,其置换样本的构造方式是:先将两个数组连接,再将连接后的数组随机打乱,然后取前 n1 个元素作为第一个数组的置换样本,取后 n2 个元素作为第二个数组的置换样本。
本练习是课程的一部分
Python 统计思维(第 2 部分)
练习说明
- 使用
np.concatenate()将两个输入数组连接为一个数组。请务必将data1和data2作为一个参数(data1, data2)传入。 - 使用
np.random.permutation()打乱连接后的数组。 - 将
permuted_data的前len(data1)个元素保存为perm_sample_1,将后len(data2)个元素保存为perm_sample_2。在实践中,可通过对permuted_data使用切片:len(data1)和len(data1):来实现。 - 返回
perm_sample_1和perm_sample_2。
交互式实操练习
通过完成这段示例代码来试试这个练习。
def permutation_sample(data1, data2):
"""Generate a permutation sample from two data sets."""
# Concatenate the data sets: data
data = ____
# Permute the concatenated array: permuted_data
permuted_data = ____
# Split the permuted array into two: perm_sample_1, perm_sample_2
perm_sample_1 = permuted_data[____]
perm_sample_2 = permuted_data[____]
return perm_sample_1, perm_sample_2