繁体   English   中英

在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM