library(magrittr)
x <- rnorm(1000, 3)
y <- 45 - 6 * x + rnorm(1000, sd = 3)
#lm(y~x) %>% summary
X <- cbind(1, x)
solve(t(X)%*%X)%*%t(X)%*%y
[,1]
44.872832
x -5.975382
sse <- function(x, y, betas){
sum((y-(betas[1] + betas[2] * x))^2)
}
sse(x,y,c(0,0))
[1] 782680.6
optim(c(0,0), sse, x = x, y=y)
$par
[1] 44.866147 -5.975136
$value
[1] 7399.005
$counts
function gradient
91 NA
$convergence
[1] 0
$message
NULL
para <- \(params, a, b){
(params[1]-3)^2/(a^2) + (params[2]+4)^2/(b^2)
}
para(c(1,2), 3, 5)
[1] 1.884444
optim(c(0,0), para, a=3, b=5)
$par
[1] 2.999949 -4.000284
$value
[1] 3.509462e-09
$counts
function gradient
79 NA
$convergence
[1] 0
$message
NULL
LS0tCnRpdGxlOiAiQ2xhc3MgMTEiCmF1dGhvcjogIklzYWFjIFF1aW50YW5pbGxhIFNhbGluYXMiCmRhdGU6ICJgciBmb3JtYXQoU3lzLnRpbWUoKSwnJW0tJWQtJVknKWAiCm91dHB1dDogCiAgaHRtbF9ub3RlYm9vazoKICAgIHRvYzogdHJ1ZQogICAgdG9jX2Zsb2F0OiB0cnVlCiAgICBjb2RlX2ZvbGRpbmc6IGhpZGUKLS0tCgpgYGB7cn0KbGlicmFyeShtYWdyaXR0cikKeCA8LSBybm9ybSgxMDAwLCAzKQp5IDwtIDQ1IC0gNiAqIHggKyBybm9ybSgxMDAwLCBzZCA9IDMpCiNsbSh5fngpICU+JSBzdW1tYXJ5CgpYIDwtIGNiaW5kKDEsIHgpCgpzb2x2ZSh0KFgpJSolWCklKiV0KFgpJSoleQoKc3NlIDwtIGZ1bmN0aW9uKHgsIHksIGJldGFzKXsKICBzdW0oKHktKGJldGFzWzFdICsgYmV0YXNbMl0gKiB4KSleMikKfQoKc3NlKHgseSxjKDAsMCkpCgpvcHRpbShjKDAsMCksIHNzZSwgeCA9IHgsIHk9eSkKCmBgYAoKYGBge3J9CgpwYXJhIDwtIFwocGFyYW1zLCBhLCBiKXsKICAocGFyYW1zWzFdLTMpXjIvKGFeMikgKyAocGFyYW1zWzJdKzQpXjIvKGJeMikKfQoKcGFyYShjKDEsMiksIDMsIDUpCgpvcHRpbShjKDAsMCksIHBhcmEsIGE9MywgYj01KQoKCgoKYGBgCg==