'Dataframe with scipy minimize function
Im trying to minimize sum square function that works with a dataframe. The df is as follows:
ds = pd.DataFrame({'t': [*np.linspace(0,300,7)], 'Ca': [0.05, 0.038, 0.0306, 0.0256, 0.0222, 0.0195, 0.0174]})
My model that Im using with sum square is:
def model(params, t, ca0=0.05):
alpha = params[0]
k = params[1]
ca_pred = (ca0**(1-alpha) - (1-alpha)*k*t)**(1/(1-alpha))
return ca_pred
def sum_of_squares(params, t, ca, ca0=0.05):
ca_pred = model(params, t, ca0)
obj = ((ca - ca_pred)**2).sum()
return obj
Initial guess:
params = [1.5, 0.05]
My specific doubt is here, I dont know how to pass dataframe to use "t" and "ca" in sum_of_squares function in minimize:
res = minimize(fun=sum_of_squares, x0=params, tol=1e-3, method="Powell")
Solution 1:[1]
You can either use the args argument:
minimize(sum_of_squares, x0=params, args=(ds['t'], ds['Ca']), tol=1e-3, method="Powell")
or wrap the function:
minimize(lambda x: sum_of_squares(x, ds["t"], ds["Ca"]), x0=params, tol=1e-3, method="Powell")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | joni |
