Posts

Showing posts from June, 2015

R 語言:邏輯回歸 Logistic Regression using R language (三)

Image
文件上有另一個多個數值變數的回歸分析的例子,這裏簡單記錄一下分析流程與結果。 有三組自變數 { w, c, wc(w+c) }, 應變數為 seeen {0,1} STEP 1. 找出相關性 > str(gorilla) 'data.frame': 49 obs. of 4 variables: $ seen: int 0 0 0 0 0 0 0 0 0 0 ... $ W : int 126 118 61 69 57 78 114 81 73 93 ... $ C : int 86 76 66 48 59 64 61 85 57 50 ... $ CW : int 64 54 44 32 42 53 41 47 33 45 ... > cor(gorilla) seen W C CW seen 1.00000000 -0.03922667 0.05437115 0.06300865 W -0.03922667 1.00000000 0.43044418 0.35943580 C 0.05437115 0.43044418 1.00000000 0.64463361 CW 0.06300865 0.35943580 0.64463361 1.00000000 > 根據上面的結果發現其相關性與 seen 甚低。 > glm.out = glm(seen ~ W*C*CW, family=binomial(logit), data=gorilla) > summary(glm.out) Call: glm(formula = seen ~ W * C * CW, family = binomial(logit), data = gorilla) Deviance Residuals: Min 1Q Median 3Q Max -1.8073 -0.9897 -0.5740 1.2368 1.7362 Coefficients: Estimate Std. Error z

R 語言:邏輯回歸 Logistic Regression using R language (二)

Image
> library('MASS') > data(menarche) > str(menarche) 'data.frame': 25 obs. of 3 variables: $ Age : num 9.21 10.21 10.58 10.83 11.08 ... $ Total : num 376 200 93 120 90 88 105 111 100 93 ... $ Menarche: num 0 0 0 2 2 5 10 17 16 29 ... > summary(menarche) Age Total Menarche Min. : 9.21 Min. : 88.0 Min. : 0.00 1st Qu.:11.58 1st Qu.: 98.0 1st Qu.: 10.00 Median :13.08 Median : 105.0 Median : 51.00 Mean :13.10 Mean : 156.7 Mean : 92.32 3rd Qu.:14.58 3rd Qu.: 117.0 3rd Qu.: 92.00 Max. :17.58 Max. :1049.0 Max. :1049.00 上頭是 R 所提供的一個很好的 Logistic Regression with One numerical predictor 的例子。 簡單的說就是有一組三個自變數分別是 age, total 以及 menarche ,中文的大意是『我們收集了一共25組女性樣本,記錄每組的平均年紀,訪問次數以及受訪者是否發生初經』。 > plot(Menarch/Total ~ Age, data=menarche) 上圖很明顯的指出 age 與 menarch rate 呈指數關係,適用於羅輯回歸。 > glm.out = glm(cbind(Menarche, Total-Menarche) ~ Age, family = binomial(logit), data=m

R 語言:邏輯回歸 Logistic Regression using R language (一)

Image
最近被 hive 搞得頭很大,加上選取的特徵量很多不確定性檔案又大,光是table砍了又建就增加了不少困難,乾脆直接取一小部分在local端用 R 做分析簡單又有效率的多(雖然可靠度降低又是另一個問題)。先前常用線性回歸,這裏記錄一下羅輯回歸的 R 如何實現。 1: library('ggplot2') 2: x <- c(-100:100) 3: y <- 1./(1.+exp(-x*0.1)) 4: df <- data.frame(x,y) 5: png('out.png') 6: g <- qplot(x,y,data=df, geom='line', color = "Exponential Dist") 7: dev.off() 一開始先列出回歸方程式  \begin{equation} y = \frac{1}{1+\exp{\beta^{T}x}}\end{equation} 有了羅輯回歸的 S-shaped / sigmoid curve 曲線圖也有了方程式較容易理解它的意思。為什麼這麼說呢?因為邏輯回歸不只是單純尋找自變數 {x} 與 應變數 {y} 的對應關係,這裏 {y} 有兩個層面上的意思:(I)機率分佈的特性。(II)亦可以理解為 binary data (dichotomous variable)。 對(I)而言,可以想像成增加一個x單位,會改變多少的機率。 對(II)而言,就形成了分類,像是 0/1 或是 輸贏。對,就是勝率(odds ratio)。 假設 $p(succeed) = \frac{\beta^Tx}{1+\beta^Tx}$, \begin{equation} odds = p(succeed)_{p(failure)} = \exp{\beta^Tx} \end{equation} 取 log的話, \begin{equation}logit = log(odds) = \beta^Tx \end{equation} 相當神奇,取個對數它又回到了線性關係上,因此我們稱 logistic regression 的 logit transfor