最小化 R 中残差平方和的最佳方法; nlm 函数是正确的方法吗?
Best way to minimize residual sum of squares in R; is nlm function the right way?
我有五个点,我将在 R 中拟合一个二阶多项式。我将通过最小化 预测的平方误差之和 (SSE) 来实现。
最好的方法是什么?
到目前为止我已经这样做了:
(1,5.8), (2,3.9), (3,4.2), (4,5.7), (5,10.2) ## my data
对于这个数据,我想拟合截距为 10 且 x^2 之前的系数设置为 1 的二阶钋。我这样做:
p<-c(5.8, 3.9, 4.2, 5.7, 10.2)
f<-function(x,a){x^2-ax+}
##sum of squared errors of prediction
SSE<-function(a){ (p[i]-f(i,a) )^2 }
nlm(SSE,0.1) ## 0.1 is picked totally random
但是returns一个"wrong"回答:
$minimum
[1] 9.475923e-25
$estimate
[1] 4.96
当我手动计算 a=4.96 的 SSE 时,SSE=9.475923e-25。我做错了什么?我最担心的是:nlm 是否通过我所有的数据点运行 运行?
我不确定 "wrong" 是什么意思。您的代码中有一些小问题,我得到的答案略有不同(a
几乎正好 = 5)。
p <- c(5.8, 3.9, 4.2, 5.7, 10.2)
x <- 1:5
f <- function(x,a){x^2-a*x+10}
##sum of squared errors of prediction
SSE <- function(a){ sum((p-f(x,a))^2) }
(n1 <- nlm(SSE,0.1)) ## 0.1 is picked totally random
## $minimum
## [1] 0.22
## $estimate
## [1] 4.999998
## $gradient
## [1] 1.443291e-10
## $code
## [1] 1
## $iterations
## [1] 3
虽然与数据点不完全匹配,但看起来很合理。
par(las=1,bty="l") ## cosmetic
plot(x,p,xlim=c(0,5.5))
xvec <- seq(0,6,length.out=100)
lines(xvec,f(xvec,n1$estimate))
您也可以通过
安装此模型
ypar <- p-x^2-10 ## subtract known terms from LHS
m1 <- lm(ypar~x-1) ## fit linear term (-1 suppresses intercept)
-1*coef(m1) ## flip sign
得到的结果正好是 5。
我有五个点,我将在 R 中拟合一个二阶多项式。我将通过最小化 预测的平方误差之和 (SSE) 来实现。
最好的方法是什么?
到目前为止我已经这样做了:
(1,5.8), (2,3.9), (3,4.2), (4,5.7), (5,10.2) ## my data
对于这个数据,我想拟合截距为 10 且 x^2 之前的系数设置为 1 的二阶钋。我这样做:
p<-c(5.8, 3.9, 4.2, 5.7, 10.2)
f<-function(x,a){x^2-ax+}
##sum of squared errors of prediction
SSE<-function(a){ (p[i]-f(i,a) )^2 }
nlm(SSE,0.1) ## 0.1 is picked totally random
但是returns一个"wrong"回答:
$minimum
[1] 9.475923e-25
$estimate
[1] 4.96
当我手动计算 a=4.96 的 SSE 时,SSE=9.475923e-25。我做错了什么?我最担心的是:nlm 是否通过我所有的数据点运行 运行?
我不确定 "wrong" 是什么意思。您的代码中有一些小问题,我得到的答案略有不同(a
几乎正好 = 5)。
p <- c(5.8, 3.9, 4.2, 5.7, 10.2)
x <- 1:5
f <- function(x,a){x^2-a*x+10}
##sum of squared errors of prediction
SSE <- function(a){ sum((p-f(x,a))^2) }
(n1 <- nlm(SSE,0.1)) ## 0.1 is picked totally random
## $minimum
## [1] 0.22
## $estimate
## [1] 4.999998
## $gradient
## [1] 1.443291e-10
## $code
## [1] 1
## $iterations
## [1] 3
虽然与数据点不完全匹配,但看起来很合理。
par(las=1,bty="l") ## cosmetic
plot(x,p,xlim=c(0,5.5))
xvec <- seq(0,6,length.out=100)
lines(xvec,f(xvec,n1$estimate))
您也可以通过
安装此模型ypar <- p-x^2-10 ## subtract known terms from LHS
m1 <- lm(ypar~x-1) ## fit linear term (-1 suppresses intercept)
-1*coef(m1) ## flip sign
得到的结果正好是 5。