R编程中的回归及其类型

2021年3月10日15:59:23 发表评论 1,081 次浏览

回归类型

R编程中主要有三种类型的回归被广泛使用。他们是：

1. 线性回归
2. 多重回归
3. 逻辑回归

线性回归

在R中实施

``````# R program to illustrate
# Linear Regression

# Height vector
x <- c (153, 169, 140, 186, 128, 136, 178, 163, 152, 133)

# Weight vector
y <- c (64, 81, 58, 91, 47, 57, 75, 72, 62, 49)

# Create a linear regression model
model <- lm (y~x)

# Print regression model
print (model)

# Find the weight of a person
# With height 182
df <- data.frame (x = 182)
res <-  predict (model, df)
cat ("\nPredicted value of a person
with height = 182")
print (res)

# Output to be present as PNG file
png (file = "linearRegGFG.png" )

# Plot
plot (x, y, main = "Height vs Weight
Regression model")
abline ( lm (y~x))

# Save the file.
dev.off ()``````

``````Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x
-39.7137       0.6847

Predicted value of a person with height = 182
1
84.9098``````

多重回归

在R中实施

R编程中的多元回归使用相同的lm()函数来创建模型。

``````# R program to illustrate
# Multiple Linear Regression

# Using airquality dataset
input <- airquality[1:50, c ( "Ozone" , "Wind" , "Temp" )]

# Create regression model
model <- lm (Ozone~Wind + Temp, data = input)

# Print the regression model
cat ( "Regression model:\n" )
print (model)

# Output to be present as PNG file
png (file = "multipleRegGFG.png" )

# Plot
plot (model)

# Save the file.
dev.off ()``````

``````Regression model:
Call:
lm(formula = Ozone ~ Wind + Temp, data = input)

Coefficients:
(Intercept)         Wind         Temp
-58.239       -0.739        1.329``````

逻辑回归

Logistic回归是另一种广泛使用的回归分析技术, 可预测范围内的值。此外, 它用于预测分类数据的值。例如, 电子邮件既可以是垃圾邮件, 也可以是非垃圾邮件, 无论是赢家还是输家, 无论是男性还是女性, 等等。

在R中实施

``````# R program to illustrate
# Logistic Regression

# Using mtcars dataset
# To create the logistic model
model <- glm (formula = vs ~ wt, family = binomial, data = mtcars)

# Creating a range of wt values
x <- seq ( min (mtcars\$wt), max (mtcars\$wt), 0.01)

# Predict using weight
y <- predict (model, list (wt = x), type = "response" )

# Print model
print (model)

# Output to be present as PNG file
png (file = "LogRegGFG.png" )

# Plot
plot (mtcars\$wt, mtcars\$vs, pch = 16, xlab = "Weight" , ylab = "VS" )
lines (x, y)

# Saving the file
dev.off ()``````

``````Call:  glm(formula = vs ~ wt, family = binomial, data = mtcars)

Coefficients:
(Intercept)           wt
5.715       -1.911

Degrees of Freedom: 31 Total (i.e. Null);  30 Residual
Null Deviance:      43.86
Residual Deviance: 31.37        AIC: 35.37``````