Reputation: 45
Im trying to fit a function described as below:
Y = 10*(b+5/c0+c1*x) assuming x is the predictor variable and Y is the predicted variable.
However, b is also an array with the same length as x and y, and it varies for each x value. I define the function as follows:
def func(x,b,c0,c1):
return 10*(b+5/c0+c1*x)
where x is the predictor variable b is an array with the same length as X (each x value has a corresponding b value) c0 and C1 are model coefficients
Im trying to perform regression between y and x using lmfit Module, however, it seems that I cannot define parameters as arrays.
The code below gives the following error:
model = Model(func)
params = model.make_params(b=data["b"].values,c0=0.429, c1=0.867)
result = model.fit(Y, params, X=x,calc_covar=True)
"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
I'm only interested in the relation between y and x, so is this way of doing it statistically wrong? Thanks
Upvotes: 0
Views: 186
Reputation: 7862
In the language of lmfit, your b
is "independent data", just like x
in that it is a predictor, not a variable to be optimized in the fit.
By default, the first argument to a model function is assumed to be the one and only independent variable. Function arguments that are not keyword arguments with a non-numerical default value will be turned into variable parameters for the fit.
But you can specify different or other independent data as with
model = Model(func, independent_vars=['x', 'b'])
params = model.make_params(c0=0.429, c1=0.867)
result = model.fit(Y, params, X=x, b=data['b'], calc_covar=True)
FWIW, the fact that b
is an array of the same length as x
is actually not important to lmfit.Model
: independent variables can be of any type. So, you could write your model function as
def func(predictor, c0, c1):
return 10*(predictor['b']+5/c0+c1*predictor['x'])
and then use that as
model = Model(func)
params = model.make_params(c0=0.429, c1=0.867)
result = model.fit(Y, params, predictor={'x':x, b: data['b']}, calc_covar=True)
That may seem like overkill here, but it can be helpful for more complex problems.
Upvotes: 1