'how to dynamically set the number of variables in SciPy's optimize.minimize
I have this code work fine to optimize multiple variables.
def f(params):
a, b, c = params
return a**2 + b**2 + c**2
initial_guess = [1, 1, 1]
result = optimize.minimize(f, initial_guess)
if result.success:
fitted_params = result.x
print(fitted_params)
else:
raise ValueError(result.message)
Is it possible to modify the code so that the number of parameters can be dynamically passed into f? For example, I'd like to have something like this.
def f(params, paramsNumber):
if paramsNumber == 3:
a, b, c = params
return a**2 + b**2 + c**2
elif paramsNumber == 2:
a, b = params
return a**2 + b**2
if paramsNumber == 3:
initial_guess = [1, 1, 1]
elif paramsNumber == 2:
initial_guess = [1, 1]
result = optimize.minimize(f, initial_guess)
if result.success:
fitted_params = result.x
print(fitted_params)
else:
raise ValueError(result.message)
Thanks a lot!
Solution 1:[1]
You can iterate over the params in your objective function, and you can use some general initialization, for your example I simply used numpy ones, that create an array with the given number of ones.
import numpy as np
from scipy import optimize
def f(params):
return sum(a**2 for a in params)
def find_sol(paramsNumber):
initial_guess = np.ones(paramsNumber)
result = optimize.minimize(f, initial_guess)
if result.success:
return result.x
raise ValueError(result.message)
find_sol(4)
array([-3.15727582e-08, -3.15727581e-08, -2.06550776e-09, -2.06550765e-09])
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 | Bob |
