最大化 R 中的非线性回归函数 [英] Maximize nonlinear regression function in R
问题描述
给定一个从函数调用reg = lm(...)
中得到的线性模型,你如何找到使得到的回归函数最大化的系数?
Given a linear model obtained from the function call reg = lm(...)
, how can you find the coefficients that maximize the obtained regression function?
我知道函数 optim(...)
,但它需要一个 函数 作为输入.我还没有想出如何从回归模型中提取这一点.
I'm aware of the function optim(...)
, but it requires a function as an input. I haven't figured out how to extract this from the regression model.
应该注意的是,我在回归分析中使用了非线性项(准确地说是平方变量).
It should be noted that I'm using non-linear terms in my regression analysis (squared variables, to be precise).
换句话说,通过回归函数看起来像
In other words, by regression function looks like
y_hat = kx_11*x_1+kx_12*x_1^2 + kx_21*x_2+kx_22*x_2^2 + ...
推荐答案
这里有一个简单的例子来演示 1 种方法.在 lm 对象上使用 predict() 来创建您的函数.fxn() 有点乱,因为我没有你的确切数据,但你应该明白.
Here is a quick example to demonstrate 1 way. Use predict() on the lm object to create your function. fxn() is a little messy since I don't have your exact data, but you should get the idea.
#set up dummy data
x1 = -10:10
x2 = runif(21)
y = -x1^2 + x1 - 10*x2^2 + runif(21)*.1
data = data.frame(y= y, x1=x1, x2=x2)
#fit model
m = lm(data=data, y ~ x1 + I(x1^2) + I(x2^2))
#define function that returns predicted value
fxn = function(z){
z = as.data.frame( t(z) )
colnames(z) = colnames(data)[-1]
predict(m, newdata=z)
}
optim(c(0,0), fxn, control=list(fnscale=-1)) #maximizes fxn
$par
[1] 4.991601e-01 -3.337561e-06
$value
[1] 0.3153461
$counts
function gradient
65 NA
$convergence
[1] 0
$message
NULL
这篇关于最大化 R 中的非线性回归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!