重抽样:蒙特卡罗模拟的一种特殊形式

Python 中的蒙特卡洛模拟

Izzy Weber

Curriculum Manager, DataCamp

重抽样:蒙特卡罗模拟的一种特殊形式

 

蒙特卡罗模拟

  • 从概率分布采样
  • 分布已知或假设
  • 依赖历史数据或专家知识选择合适分布

 

重抽样

  • 从现有数据随机抽样
  • 现有数据代表一个隐含的概率分布
  • 假设数据具代表性
Python 中的蒙特卡洛模拟

重抽样方法

  1. 不放回抽样
    • 用于抽取随机样本
  2. 放回抽样(自助法)
    • 用于估计几乎任意统计量的抽样分布
  3. 置换检验
    • 常用于比较两组
Python 中的蒙特卡洛模拟

不放回抽样

随机抽取新英格兰六州中的两个不同州

import random
def two_random_ne_states():

ne_states=["Maine", "Vermont", "New Hampshire", "Massachusetts", "Connecticut", "Rhode Island"]
return(random.sample(ne_states, 2))

 

 

two_random_ne_states()
two_random_ne_states()
['Massachusetts', 'Connecticut']
['New Hampshire', 'Maine']
Python 中的蒙特卡洛模拟

自助法(放回抽样)

估计 NBA 球员身高均值的 95% 置信区间

import random
import numpy as np

nba_heights = [196, 191, 198, 216, 188, 185, 211, 201,
               188, 191, 201, 208, 191, 183, 196]
simu_heights = []

for i in range(1000): bootstrap_sample = random.choices(nba_heights, k=15) simu_heights.append(np.mean(bootstrap_sample))
upper = np.quantile(simu_heights, 0.975) lower = np.quantile(simu_heights, 0.025) print([np.mean(simu_heights), lower, upper])
[196.26666666666668, 191.8, 201.2]
Python 中的蒙特卡洛模拟

自助法结果可视化

绘图库:

  • seaborn
  • matplotlib
import seaborn as sns
import matplotlib.pyplot as plt

sns.displot(simu_heights)
plt.axvline(191.8, color="red")
plt.axvline(201.2, color="red")
plt.axvline(196.3, color="green")

 

模拟身高的分布图

Python 中的蒙特卡洛模拟

置换检验

估计 NBA 球员与美国男性身高均值差的 95% 置信区间

us_heights = [165, 185, 179, 187, 193, 180, 178, 179, 171, 176, 
              169, 160, 140, 199, 176, 185, 175, 196, 190, 176]
nba_heights = [196, 191, 198, 216, 188, 185, 211, 201, 188, 191, 201, 208, 191, 183, 196]

all_heights = us_heights + nba_heights
simu_diff = [] for i in range(1000): perm_sample = np.random.permutation(all_heights) perm_nba, perm_adult = perm_sample[0:15], perm_sample[15:35]
perm_diff = np.mean(perm_nba) - np.mean(perm_adult) simu_diff.append(perm_diff)
Python 中的蒙特卡洛模拟

置换检验结果

NBA 与美国成年男性身高均值之差:

np.mean(nba_heights) - np.mean(us_adult_height)
18.31666666666669

两随机列表置换的 95% 置信区间:

upper = np.quantile(simu_diff, 0.975)
lower = np.quantile(simu_diff, 0.025)
print([lower, upper])
[-10.033333333333331, 10.033333333333331]
Python 中的蒙特卡洛模拟

置换结果可视化

sns.distplot(simu_diff)
plt.axvline(-10.03, color="red")
plt.axvline(10.03, color="red")
plt.axvline(18.32, color="green")

模拟身高差的分布图

Python 中的蒙特卡洛模拟

Passons à la pratique !

Python 中的蒙特卡洛模拟

Preparing Video For Download...