使用R语言进行简单的线性回归

线性回归

前置知识

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")

posted @ 2020-08-01 19:30  _starsky  阅读(1731)  评论(0编辑  收藏  举报