模仿 R 中 Python 的最小化函数

Mimic minimize function from Python in R

我有以下数据点:

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)]

我的主要问题是无法跟踪数据更改流。 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 中 Std 得到的结果是:

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

我试图在 R 或 Excel 中复制相同的结果。任何一个都足够了。我遇到的问题是我无法准确模仿与 minimize(最小化最小二乘)和 residual 相同的行为。我尝试使用 minimizeresidual 函数在 R 中搜索相应的库;但是,我无法找到任何(也无法正确使用)给我与 Python 中相同的结果。

当我绘制 xdataydataminimize 的结果(我在上面提供的)时,我在 Python 中得到以下图表。最后,我只想在 R 或 Excel 中重现同一张图。

如何进行?我不是 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))

我使用您的参数起始值,尽管这些不是模型确定的值。要在控制台中查看参数类型 nls.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