R 优化拟合系数以获得更好的拟合效果

R 优化拟合系数以获得更好的拟合效果,r,curve-fitting,nls,nonlinear-optimization,R,Curve Fitting,Nls,Nonlinear Optimization,我正在使用minpack.lm包运行非线性最小二乘法 但是,对于数据中的每个组,我希望优化最小化拟合参数,类似于Python的函数 最小化函数是用于运行 优化问题。它需要一个目标函数,即函数 计算要最小化的数组、参数对象和 几个可选参数 我之所以需要它,是因为我想根据获得的拟合参数优化拟合函数,以找到可以拟合数据中两组的全局拟合参数 这是我目前适合分组的方法 df <- data.frame(y=c(replicate(2,c(rnorm(10,0.18,0.01), rnorm(10,0

我正在使用minpack.lm包运行非线性最小二乘法

但是,对于数据中的每个组,我希望优化最小化拟合参数,类似于Python的函数

最小化函数是用于运行 优化问题。它需要一个目标函数,即函数 计算要最小化的数组、参数对象和 几个可选参数

我之所以需要它,是因为我想根据获得的拟合参数优化拟合函数,以找到可以拟合数据中两组的全局拟合参数

这是我目前适合分组的方法

df <- data.frame(y=c(replicate(2,c(rnorm(10,0.18,0.01), rnorm(10,0.17,0.01))), 
                                c(replicate(2,c(rnorm(10,0.27,0.01), rnorm(10,0.26,0.01))))),
                         DVD=c(replicate(4,c(rnorm(10,60,2),rnorm(10,80,2)))),
                         gr = rep(seq(1,2),each=40),logic=rep(c(1,0),each=40))
这些群的拟合方程为

fitt <- function(data) {
  fit <- nlsLM(y~pi*label2*(DVD/2+U1)^2,
               data=data,start=c(label2=1,U1=4),trace=T,control = nls.lm.control(maxiter=130))
}

library(minpack.lm)
library(plyr)  # will help to fit in groups

fit <- dlply(df, c('gr'), .fun = fitt)  #,"Die" only grouped by Waferr

> fit
$`1`
Nonlinear regression model
  model: y ~ pi * label2 * (DVD/2 + U1)^2
   data: data
   label2        U1 
2.005e-05 1.630e+03 
$`2`
label2      U1 
 2.654 -35.104   
我需要知道是否有任何函数可以优化平方和以获得两组的最佳拟合。 我们可能会说,你已经有了作为残差平方和的最佳拟合参数,但我知道这可以做到,但我还没有找到任何类似的例子,我们可以在R中做到这一点


注:我用数字和拟合线组成了它。

不确定r,但使用共享参数的最小二乘法通常很容易实现

一个简单的python示例如下所示:

import matplotlib
matplotlib.use('Qt4Agg')
from matplotlib import pyplot as plt

from random import random
from scipy import optimize
import numpy as np

#just for my normal distributed errord
def boxmuller(x0,sigma):
    u1=random()
    u2=random()
    ll=np.sqrt(-2*np.log(u1))
    z0=ll*np.cos(2*np.pi*u2)
    z1=ll*np.cos(2*np.pi*u2)
    return sigma*z0+x0, sigma*z1+x0

#some non-linear function
def f0(x,a,b,c,s=0.05):
    return a*np.sqrt(x**2+b**2)-np.log(c**2+x)+boxmuller(0,s)[0]

# residual function for least squares takes two data sets. 
# not necessarily same length
# two of three parameters are common
def residuals(parameters,l1,l2,dataPoints):
    a,b,c1,c2 = parameters
    set1=dataPoints[:l1]
    set2=dataPoints[-l2:]
    distance1 = [(a*np.sqrt(x**2+b**2)-np.log(c1**2+x))-y for x,y in set1]
    distance2 = [(a*np.sqrt(x**2+b**2)-np.log(c2**2+x))-y for x,y in set2]
    res = distance1+distance2
    return res

xList0=np.linspace(0,8,50)
#some xy data
xList1=np.linspace(0,7,25)
data1=np.array([f0(x,1.2,2.3,.33) for x in xList1])
#more xy data using different third parameter
xList2=np.linspace(0.1,7.5,28)
data2=np.array([f0(x,1.2,2.3,.77) for x in xList2])
alldata=np.array(zip(xList1,data1)+zip(xList2,data2))

# rough estimates
estimate = [1, 1, 1, .1]
#fitting; providing second length is actually redundant
bestFitValues, ier= optimize.leastsq(residuals, estimate,args=(len(data1),len(data2),alldata))
print bestFitValues


fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xList1, data1)
ax.scatter(xList2, data2)
ax.plot(xList0,[f0(x,bestFitValues[0],bestFitValues[1],bestFitValues[2] ,s=0) for x in xList0])
ax.plot(xList0,[f0(x,bestFitValues[0],bestFitValues[1],bestFitValues[3] ,s=0) for x in xList0])


plt.show()

#output
>> [ 1.19841984  2.31591587  0.34936418  0.7998094 ]

如果需要,你甚至可以自己最小化。如果您的参数空间表现良好,即近似抛物线最小值,那么简单的参数空间就可以了。

我认为?optim相当于Python的最小化。optim的作者推荐optimx包做了很好的改进。@Gregor我明白了。我很抱歉让你们讨厌。我只是被绊倒了,在这个问题上真的需要帮助@Gregor我从来没有听说过optimx。我快速查看了stackoverflow,但似乎没有针对分组数据的optimx方法。optim和optimx都最小化了任意函数。我认为你需要澄清你所说的同时优化这两个拟合参数是什么意思——是否有某些参数你希望在组之间相同?您希望您的结果与单独拟合组有什么不同?我想如果你正确地指定了你的模型,你可能可以用nls做你想做的事…@Gregor我希望nls能做到。所以我不会拼命寻找另一个解决方案。问题是,当我用python进行拟合时,我可以用单个拟合系数为这两个组得到合适的拟合线。我猜我用“将这两个拟合参数一起优化”的说法是错误的,我编辑了OP!