13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

创新互联R语言教程:R语言线性回归

回归分析是一种非常广泛使用的统计工具,用于建立两个变量之间的关系模型。 这些变量之一称为预测变量,其值通过实验收集。 另一个变量称为响应变量,其值从预测变量派生。

10年建站经验, 成都网站制作、网站建设、外贸网站建设客户的见证与正确选择。成都创新互联提供完善的营销型网页建站明细报价表。后期开发更加便捷高效,我们致力于追求更美、更快、更规范。

在线性回归中,这两个变量通过方程相关,其中这两个变量的指数(幂)为1.数学上,线性关系表示当绘制为曲线图时的直线。 任何变量的指数不等于1的非线性关系将创建一条曲线。

线性回归的一般数学方程为 -

y = ax + b

以下是所使用的参数的描述 -

建立回归的步骤

回归的简单例子是当人的身高已知时预测人的体重。 为了做到这一点,我们需要有一个人的身高和体重之间的关系。

创建关系的步骤是 -

输入数据

下面是代表观察的样本数据 -

# Values of height
151, 174, 138, 186, 128, 136, 179, 163, 152, 131

# Values of weight.
63, 81, 56, 91, 47, 57, 76, 72, 62, 48

LM()函数

此函数创建预测变量和响应变量之间的关系模型。

语法

线性回归中lm()函数的基本语法是 -

lm(formula,data)

以下是所使用的参数的说明 -

创建关系模型并获取系数

x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)

# Apply the lm() function.
relation <- lm(y~x)

print(relation)

当我们执行上面的代码,它产生以下结果 -

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x  
   -38.4551          0.6746 

获取相关的摘要

x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)

# Apply the lm() function.
relation <- lm(y~x)

print(summary(relation))

当我们执行上面的代码,它产生以下结果 -

Call:
lm(formula = y ~ x)

Residuals:
    Min      1Q     Median      3Q     Max 
-6.3002    -1.6629  0.0412    1.8944  3.9775 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) -38.45509    8.04901  -4.778  0.00139 ** 
x             0.67461    0.05191  12.997 1.16e-06 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.253 on 8 degrees of freedom
Multiple R-squared:  0.9548,    Adjusted R-squared:  0.9491 
F-statistic: 168.9 on 1 and 8 DF,  p-value: 1.164e-06

predict()函数

语法

线性回归中的predict()的基本语法是 -

predict(object, newdata)

以下是所使用的参数的描述 -

预测新人的体重

# The predictor vector.
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)

# The resposne vector.
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)

# Apply the lm() function.
relation <- lm(y~x)

# Find weight of a person with height 170.
a <- data.frame(x = 170)
result <-  predict(relation,a)
print(result)

当我们执行上面的代码,它产生以下结果 -

       1 
76.22869 

以图形方式可视化回归

# Create the predictor and response variable.
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
relation <- lm(y~x)

# Give the chart file a name.
png(file = "linearregression.png")

# Plot the chart.
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")

# Save the file.
dev.off()

当我们执行上面的代码,它产生以下结果 -


当前题目:创新互联R语言教程:R语言线性回归
网站URL:http://cdbrznjsb.com/article/copsghj.html

其他资讯

让你的专属顾问为你服务