R语言 教程
- 第1节:R语言 概述
- 第2节:R语言 环境设置
- 第3节:R语言 基本语法
- 第4节:R语言 数据类型
- 第5节:R语言 变量
- 第6节:R语言 运算符
- 第7节:R语言 决策
- 第8节:R语言 包
- 第9节:R语言 循环
- 第10节:R语言 数据重塑
- 第11节:R语言 函数
- 第12节:R语言 字符串
- 第13节:R语言 向量
- 第14节:R语言 列表
- 第15节:R语言 矩阵
- 第16节:R语言 数组
- 第17节:R语言 因子
- 第18节:R语言 数据帧
- 第19节:R语言 条形图
- 第20节:R语言 箱线图
- 第21节:R语言 直方图
- 第22节:R语言 折线图
- 第23节:R语言 散点图
- 第24节:R语言 饼状图
- 第25节:R语言 CSV文件
- 第26节:R语言 Excel文件
- 第27节:R语言 二进制文件
- 第28节:R语言 XML文件
- 第29节:R语言 JSON文件
- 第30节:R语言 Web数据
- 第31节:R语言 数据库
- 第32节:R语言 平均值,中位数和模式
- 第33节:R语言 线性回归
- 第34节:R语言 多重回归
- 第35节:R语言 逻辑回归
- 第36节:R语言 标准分布
- 第37节:R语言 二项分布
- 第38节:R语言 泊松回归
- 第39节:R语言 协方差分析
- 第40节:R语言 时间序列分析
- 第41节:R语言 非线性最小二乘
- 第42节:R语言 决策树
- 第43节:R语言 随机森林算法
- 第44节:R语言 生存分析
- 第45节:R语言 卡方检验
R语言 非线性最小二乘
当模拟真实世界数据用于回归分析时,我们观察到,很少情况下,模型的方程是给出线性图的线性方程。大多数时候,真实世界数据模型的方程涉及更高程度的数学函数,如3的指数或sin函数。在这种情况下,模型的图给出了曲线而不是线。线性和非线性回归的目的是调整模型参数的值,以找到最接近您的数据的线或曲线。在找到这些值时,我们将能够以良好的精确度估计响应变量。
在最小二乘回归中,我们建立了一个回归模型,其中来自回归曲线的不同点的垂直距离的平方和被最小化。我们通常从定义的模型开始,并假设系数的一些值。然后我们应用R语言的nls()函数获得更准确的值以及置信区间。
语法
在R语言中创建非线性最小二乘测试的基本语法是 -
nls(formula, data, start)
以下是所使用的参数的描述 -
formula是包括变量和参数的非线性模型公式。
data是用于计算公式中变量的数据框。
start是起始估计的命名列表或命名数字向量。
例
我们将考虑一个假设其系数的初始值的非线性模型。 接下来,我们将看到这些假设值的置信区间是什么,以便我们可以判断这些值在模型中有多好。
所以让我们考虑下面的方程为这个目的 -
a = b1*x^2+b2
让我们假设初始系数为1和3,并将这些值拟合到nls()函数中。
xvalues <- c(1.6,2.1,2,2.23,3.71,3.25,3.4,3.86,1.19,2.21)
yvalues <- c(5.19,7.43,6.94,8.11,18.75,14.88,16.06,19.12,3.21,7.58)
# Give the chart file a name.
png(file = "nls.png")
# Plot these values.
plot(xvalues,yvalues)
# Take the assumed values and fit into the model.
model <- nls(yvalues ~ b1*xvalues^2+b2,start = list(b1 = 1,b2 = 3))
# Plot the chart with new data by fitting it to a prediction from 100 data points.
new.data <- data.frame(xvalues = seq(min(xvalues),max(xvalues),len = 100))
lines(new.data$xvalues,predict(model,newdata = new.data))
# Save the file.
dev.off()
# Get the sum of the squared residuals.
print(sum(resid(model)^2))
# Get the confidence intervals on the chosen values of the coefficients.
print(confint(model))
当我们执行上面的代码,它产生以下结果 -
[1] 1.081935
Waiting for profiling to be done...
2.5% 97.5%
b1 1.137708 1.253135
b2 1.497364 2.496484
我们可以得出结论,b1的值更接近1,而b2的值更接近2而不是3。