问题描述:

I would like to use DEoptim to minimize the square error of the given function to fit a 4 parameter power law to some data:

expfun <- function(p,data){

res = eval(expression(((data[,2]-((p[1]+p[2]*data[,1])*(1-exp(-(data[,1]-p[3])/p[4]))))^2)))

return(sum(res))

}

low = c(-100,-50,-50,0)

high = c(100,50,50,20)

fit = DEoptim(expfun, low, high, DEoptim.control(itermax=500, trace=False))

But I'm not sure how to make the data available to DEoptim when expfun is passed. What is the correct way to do this?

EDIT: Here is some (mock) data I can provide... I am not so familiar with R but am interfacing with it through python at the moment. A small clip of my input matrix, data, looks like this (from a pandas dataframe):

 x y

0 33.8 19.734328

1 34.2 19.855713

2 34.4 20.005075

3 36.0 20.023766

4 36.1 20.921509

5 36.3 21.505115

6 36.6 24.600343

7 36.8 25.424239

8 37.4 26.335077

9 38.2 26.421332

10 41.6 26.729980

11 42.4 35.006403

12 46.0 37.647034

13 47.3 38.058187

14 47.8 38.177062

15 58.5 41.061019

16 79.1 43.005465

My data is loaded in through two numpy arrays x and y (again python) into a FloatVector:

m = np.concatenate((x,y))

data = matrix(R.FloatVector(m), len(x))

which gives this information if I output it in a console:

<Matrix - Python:0x000000001316B948 / R:0x0000000011FCC4C0>

[19.734328, 19.855713, 20.005075, ..., 38.177062, 41.061019, 43.005465]

I don't know how useful this extra information will be but I hope it helps

网友答案:

If you look at ?DEoptim, there is an argument called ..., for which it says that the arguments passed to ... will be passed on to fn. Consequently, I would do it like so:

my.data <- read.table(text = "x       y
33.8    19.734328
34.2    19.855713
34.4    20.005075
36.0    20.023766
36.1    20.921509
36.3    21.505115
36.6    24.600343
36.8    25.424239
37.4    26.335077
38.2    26.421332
41.6    26.729980
42.4    35.006403
46.0    37.647034
47.3    38.058187
47.8    38.177062
58.5    41.061019
79.1    43.005465", header = TRUE)

expfun <- function(p, data){
  res = (data[,2]-((p[1]+p[2]*data[,1])*(1-exp(-(data[,1]-p[3])/p[4]))))^2
  sum(res)
}

low = c(-100,-50,-50,0)
high = c(100,50,50,20)

require(DEoptim)
fit = DEoptim(expfun, low, high, DEoptim.control(itermax=500, trace = FALSE), data = my.data)
summary(fit)

***** summary of DEoptim object ***** 
best member   :  72.03075 -0.33433 27.12013 18.7239 
best value    :  55.70625 
after         :  500 generations 
fn evaluated  :  1002 times 
*************************************
相关阅读:
Top