模仿从R中最小化Python的function

我有以下数据点:

xdata看起来如下所示。

 1000.00 300.00 100.00 30.00 10.00 3.00 1.00 0.30 0.10 0.03 0.01 0.00 

ydata看起来像下面这样。

 91.8 95.3 100 123 203 620 1210 1520 1510 1520 1590 1620 

我在python中运行以下命令:

 results = minimize(fit.dataFit,cParams,args=(xdata,np.array(ydata))) curve = np.array(ydata)+results.residual Std = [list(i) for i in zip(xdata,ydata, curve)] 

我的主要问题是无法跟踪数据更改的stream。 dataFit执行以下操作:

y_model = (ymax*xdata / (ec50 + xdata)) + Ns* xdata + ymin return y_model - ydata

哪里

  1. ymax = 1624.75
  2. ymin = 91.85
  3. ec50 = 3
  4. Ns = 0.2045514

最后,从下面的库中调用最小化:

from lmfit import minimize,Minimizer,Parameters,Parameter,report_errors,report_fit

我在python中得到的结果是:

 110 49.1 52.4 121 299 688 1110 1420 1550 1590 1610 1620 

我想在R或Excel中复制相同的结果。 任何一个都足够了。 我遇到的问题是,我无法准确地模仿与minimize (即最小化最小二乘)和residual相同的行为。 我已经尝试在R中search相应的库,并使用minimizeresidual函数; 然而,我没有find任何(也没有正确使用),给了我和Python一样的结果。

当我绘制xdataydataminimize结果(我已经在上面提供)时,我在Python中得到了下面的图。 最终,我只想在R或Excel中重现这个相同的graphics。 在这里输入图像说明

如何进行? 我不是Python的专家,因此,我无法正确地将代码从Python移植到R或Excel。

你可以使用函数nls()在R中复制它。 首先,我设置你的数据,这样它可以被读入R.

 ## Replicate results from Python `minimize` with R `nls()` # First I load your data in df <- data.frame(xdata = c(1000.00,300.00,100.00,30.00,10.00,3.00,1.00,0.30, 0.10,0.03,0.01,0.00), ydata = c(91.8,95.3,100,123,203,620,1210,1520,1510,1520,1590, 1620)) # Now we estimate the model via nonlinear least squares nls.fit <- nls(ydata ~ (ymax*xdata / (ec50 + xdata)) + Ns*xdata + ymin, data=df, start=list(ymax=1624.75, ymin = 91.85, ec50 = 3, Ns = 0.2045514)) 

我使用你的参数的初始值,虽然这些不是模型的价值观。 要在控制台中查看参数typesnls.fit ,R将显示有关拟合模型的信息。

 df$nls.pred <- fitted(nls.fit) # We extract the predicted values of the model head(df) # We can examine the values of `xdata`, `ydata` and our predictions xdata ydata nls.pred 1 1000 91.8 109.48985 2 300 95.3 49.02029 3 100 100.0 52.29715 4 30 123.0 120.61060 5 10 203.0 298.55367 6 3 620.0 687.63743 # We can see that the values we have obtained are very close to # what you obtained in the variable you named Std in python. # I now load the ggplot2 library to recreate your plot library(ggplot2) ggplot(df, aes(xdata, ydata))+geom_point(color='red')+ geom_line(data=df, aes(xdata, nls.pred))+ theme_classic()+ # This makes the background black and white as in your plot scale_x_log10() # The axis in your post is logged