自助法入門

R 的抽樣

Richie Cotton

Data Evangelist at DataCamp

有放回,或不放回

不放回抽樣

賭桌上的撲克牌。

有放回抽樣(「重抽樣」)

四顆轉動中的骰子。

R 的抽樣

不放回的簡單隨機抽樣

母體

排成列與行的咖啡豆。

樣本

排成列與行的咖啡豆,多數呈灰色。

R 的抽樣

有放回的簡單隨機抽樣

母體

排成列與行的咖啡豆。

樣本

隨機抽出的咖啡豆,其中有重複。

R 的抽樣

為何要有放回抽樣?

  • coffee_ratings 資料視為所有咖啡這個更大母體中的一個樣本。
  • 將樣本中的每顆咖啡豆,視為代表母體中許多我們未觀測到的咖啡。
  • 有放回抽樣可近似把這些群體中的不同成員納入樣本。
R 的抽樣

咖啡資料前處理

coffee_focus <- coffee_ratings %>%
  select(variety, country_of_origin, flavor) %>%
  rowid_to_column()
glimpse(coffee_focus)
Rows: 1,338
Columns: 4
$ rowid             <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ...
$ variety           <chr> NA, "Other", "Bourbon", NA, "Other", NA, "Other", N...
$ country_of_origin <chr> "Ethiopia", "Ethiopia", "Guatemala", "Ethiopia", "E...
$ flavor            <dbl> 8.83, 8.67, 8.50, 8.58, 8.50, 8.42, 8.50, 8.33, 8.6...
R 的抽樣

用 slice_sample() 重抽樣

coffee_resamp <- coffee_focus %>%
  slice_sample(prop = 1, replace = TRUE)
# A tibble: 1,338 x 4
   rowid variety country_of_origin flavor
   <int> <chr>   <chr>              <dbl>
 1  1253 Bourbon Guatemala           6.92
 2   186 Caturra Colombia            7.58
 3  1185 Bourbon Guatemala           7.42
 4  1273 NA      Philippines         6.5 
 5  1042 Caturra Honduras            7.33
 6   195 Caturra Guatemala           7.75
 7  1219 Typica  Mexico              7   
 8   952 Caturra Honduras            7.5 
 9    41 Caturra Thailand            8.33
10   460 Caturra Honduras            7.67
# ... with 1,328 more rows
R 的抽樣

重複出現的咖啡豆

coffee_resamp %>% 
  count(rowid, sort = TRUE)
# A tibble: 844 x 2
   rowid     n
   <int> <int>
 1   704     5
 2   913     5
 3  1070     5
 4    16     4
 5   180     4
 6   230     4
 7   234     4
 8   342     4
 9   354     4
10   423     4
# ... with 834 more rows
R 的抽樣

未抽到的咖啡豆

coffee_resamp %>% 
  summarize(
    coffees_included = n_distinct(rowid),
    coffees_not_included = n() - coffees_included
  )
# A tibble: 1 x 2
  coffees_included coffees_not_included
             <int>                <int>
1              844                  494
R 的抽樣

自助法(Bootstrapping)

與自母體抽樣相反。

抽樣:從母體取到較小的樣本。

自助法:用你的樣本建構一個理論母體。

自助法的用途

  • 只用單一樣本來理解抽樣變異。

一隻牛仔靴。

R 的抽樣

自助法流程

  1. 建立與原樣本同大小的重抽樣。
  2. 計算此自助樣本的目標統計量。
  3. 重複步驟 1 與 2 多次。

得到的統計量稱為「自助統計量」,觀察其變異所形成的是「自助分配」。

R 的抽樣

自助法估計咖啡平均風味

# Step 3. Repeat many times
mean_flavors_1000 <- replicate(
  n = 1000,
  expr = {
    coffee_focus %>%
      # Step 1. Resample
      slice_sample(prop = 1, replace = TRUE) %>%
      # Step 2. Calculate statistic
      summarize(mean_flavor = mean(flavor, na.rm = TRUE)) %>% 
      pull(mean_flavor)
  })
R 的抽樣

自助分配的長條圖

bootstrap_distn <- tibble(
  resample_mean = mean_flavors_1000
)
ggplot(bootstrap_distn, aes(resample_mean)) +
  geom_histogram(binwidth = 0.0025)

樣本平均的自助分配長條圖。

R 的抽樣

一起來練習吧!

R 的抽樣

Preparing Video For Download...