常態分配

R 中的混合模型

Victor Medina

Researcher at The University of Edinburgh

性別資料集的混合模型

R 中的混合模型

適配混合模型的套件

  • mixtools
    • 未實作 Poisson 分配。
  • bayesmix
    • 貝氏推論不在本課範圍內。
  • EMCluster
    • 僅支援常態分配。
  • flexmix
    • 具備所需分配,並可彈性建立更複雜模型。
R 中的混合模型

常態分配的性質

平均數

標準差

R 中的混合模型

從常態分配取樣

從常態分配產生樣本:

  • rnorm(n, mean, sd)

範例:從平均 10、標準差 5 的常態分配產生 100 個值

 

> population_sample <- rnorm(n = 100, mean = 10, sd = 5)
> head(population_sample)
[1]  6.248874  9.564190 16.006521  9.139647 10.114969 16.423538
R 中的混合模型

平均數的估計

  • 未知平均與標準差,只知道觀測值
    • 需從觀測值中估計
  • 估計平均可計算樣本平均

 

> mean_estimate <- mean(population_sample)
10.35759
R 中的混合模型

估計 sd 可依下列步驟:

$$value_i\rightarrow (. -mean\_estimate)\rightarrow (.)^2\rightarrow mean (.)\rightarrow \sqrt{(.)}$$

> population_sample %>%  
+   subtract(mean_estimate) %>%
+   raise_to_power(2) %>% mean() %>% sqrt()
5.318641
  • 使用 sd 函式
> standard_deviation_estimate <- sd(population_sample)
> standard_deviation_estimate
5.345435
R 中的混合模型

視覺化估計的常態分配

# 將樣本轉成資料框
population_sample <- data.frame(x = population_sample)

# 繪製長條圖
ggplot(data = population_sample) + 
   geom_histogram(aes(x = x, y = ..density..)) +
   stat_function(geom = "line", 
                 fun = dnorm, 
                 args = list(mean = mean_estimate, 
                             sd = standard_deviation_estimate))
R 中的混合模型

R 中的混合模型

一起來練習吧!

R 中的混合模型

Preparing Video For Download...