線性回歸
前置知識
1. lm 函數
lm函數是用於創建線性模型的函數,此函數可以床架預測變量和相應變量之間的關系模型
lm(formula , data)
以下是所使用的參數的說明:
公式是表示 x 和 y 之間的關系的符號
數據是應用公式的向量
線性回歸的簡單的小例子
x <- c(2 , 4 , 6 , 8)
y <- c(1 , 2 , 3 , 4)
relation <- lm(y~x)
relation
運行結果:
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
0.0 0.5
上面的 Intercept 我初步斷定其為那個 (w , b) 中的 b 參數 , 而 x 下面的那個是系數 w 。
我們使用summary() 函數查看一下相關摘要
summary(relation)
運行結果:
Call:
lm(formula = y ~ x)
Residuals:
1 2 3 4
0 0 0 0
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.0 0.0 NA NA
x 0.5 0.0 Inf <2e-16 ***
---
Signif. codes:
0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0 on 2 degrees of freedom
Multiple R-squared: 1, Adjusted R-squared: 1
F-statistic: Inf on 1 and 2 DF, p-value: < 2.2e-16
使用求出來的線性模型進行預測
testdata <- c(5 , 12 , 30)
test <- data.frame(x = testdata)
res <- predict(relation , test)
res
運行結果:
1 2 3
2.5 6.0 15.0
我們發現結果和預想的一致
通過畫圖展示測試數據的線性關系
plot(y,x,col = "blue",main = "Height & Weight Regression",
abline(lm(x~y)),cex = 1.3,pch = 16,xlab = "Weight in Kg",ylab = "Height in cm")