自助抽樣入門

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. 計算此 bootstrap 樣本的目標統計量
  3. 重複步驟 1、2 多次

得到的統計量稱為「bootstrap 統計量」,它們形成「bootstrap 分配」

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 中的抽樣

Bootstrap 分配直方圖

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

平均風味的 bootstrap 分配

Python 中的抽樣

一起來練習吧!

Python 中的抽樣

Preparing Video For Download...