自助法简介

Python 抽样

James Chapman

Curriculum Manager, DataCamp

有放回还是无放回

不放回抽样:

赌场桌上的扑克牌。

有放回抽样("重抽样"):

四个滚动的骰子。

Python 抽样

简单随机抽样(不放回)

总体:

按行列排列的咖啡豆。

样本:

按行列排列的咖啡豆,大部分呈灰色。

Python 抽样

简单随机抽样(有放回)

总体:

按行列排列的咖啡豆。

重抽样:

随机抽取的咖啡豆,其中一些有重复。

Python 抽样

为何要有放回抽样?

  • coffee_ratings:来自所有咖啡总体的一个样本
  • 样本中的每款咖啡代表许多假想的总体咖啡
  • 有放回抽样可作替代
Python 抽样

咖啡数据准备

coffee_focus = coffee_ratings[["variety", "country_of_origin", "flavor"]]
coffee_focus = coffee_focus.reset_index()
      index  variety country_of_origin  flavor
0         0     None          Ethiopia    8.83
1         1    Other          Ethiopia    8.67
2         2  Bourbon         Guatemala    8.50
3         3     None          Ethiopia    8.58
4         4    Other          Ethiopia    8.50
...     ...      ...               ...     ...
1333   1333     None           Ecuador    7.58
1334   1334     None           Ecuador    7.67
1335   1335     None     United States    7.33
1336   1336     None             India    6.83
1337   1337     None           Vietnam    6.67

[1338 rows x 4 columns]
Python 抽样

用 .sample() 重抽样

coffee_resamp = coffee_focus.sample(frac=1, replace=True)
      index  variety country_of_origin  flavor
1140   1140  Bourbon         Guatemala    7.25
57       57  Bourbon         Guatemala    8.00
1152   1152  Bourbon            Mexico    7.08
621     621  Caturra          Thailand    7.50
44       44     SL28             Kenya    8.08
...     ...      ...               ...     ...
996     996   Typica            Mexico    7.33
1090   1090  Bourbon         Guatemala    7.33
918     918    Other         Guatemala    7.42
249     249  Caturra          Colombia    7.67
467     467  Caturra          Colombia    7.50

[1338 rows x 4 columns]
Python 抽样

重复的咖啡

coffee_resamp["index"].value_counts()
658     5
167     4
363     4
357     4
1047    4
       ..
771     1
770     1
766     1
764     1
0       1
Name: index, Length: 868, dtype: int64
Python 抽样

缺失的咖啡

num_unique_coffees = len(coffee_resamp.drop_duplicates(subset="index"))
868
len(coffee_ratings) - num_unique_coffees
470
Python 抽样

自助法(Bootstrapping)

与从总体抽样相反

"抽样":从总体到较小的样本

"自助法":用样本构建理论总体

自助法用途:

  • 仅用一个样本理解抽样变异性

一只牛仔靴。

Python 抽样

自助法流程

  1. 生成与原样本同大小的重抽样
  2. 计算该自助样本的目标统计量
  3. 多次重复步骤 1 和 2

得到的统计量称为"自助统计量",形成"自助分布"

Python 抽样

咖啡风味均值的自助法

import numpy as np

mean_flavors_1000 = []
for i in range(1000):
mean_flavors_1000.append(
np.mean(coffee_sample.sample(frac=1, replace=True)['flavor'])
)
Python 抽样

自助分布直方图

import matplotlib.pyplot as plt
plt.hist(mean_flavors_1000)
plt.show()

均值风味的自助分布

Python 抽样

Passons à la pratique !

Python 抽样

Preparing Video For Download...