I try to generalize an optimization function using scipy.optimize.
Actually I write this function in this way:
def value_to_optimize(data):
data_set = np.genfromtxt('myfilepathinstaticmode', delimiter=',',skip_header=1)
doe = data_set[:,:-1]
new_data_set = np.vstack((np.array(doe),np.array(data)))
return result_of_another_function(new_data_set)
def new_data():
rst = minimize(value_to_optimize,[0,0])
return rst.x
the function I try to optimize is the first one. And to do that I use the second function that use "minimize" and a x0 for starting optimization.
As you can see my problem is comming from 'myfilepathinstaticmode'. I would like to generalize my function, like value-to_optimize(filename,data), but at this moment, I cannot apply optimize() on it because it is only working on numbers.
Any idea on how to write it in a generalized manner ?
CodePudding user response:
I personally would read the data outside of the minimizer function and then hand over only that data into the method:
def value_to_optimize(data, doe):
new_data_set = np.vstack((np.array(doe),np.array(data)))
return result_of_another_function(new_data_set)
def new_data():
data_set = np.genfromtxt('myfilepathinstaticmode', delimiter=',',skip_header=1)
doe = data_set[:,:-1]
rst = minimize(value_to_optimize, ([0,0], doe))
return rst.x
EDIT: I'm not sure if I understood your question correctly. So, alternatively, a more flexible approach would be to use functools.partial to generate a method with the filename as a parameter which you can then hand over to your optimizer.
CodePudding user response:
Something is working in this way. I'm not convinced about the robustess of the code. The solution: I defined the function value_to_optimize() inside the function new_data(). Like this, the parameter 'filename' is out of "value_to_optimize()" but is a kind of "global" assignment inside new_data().
def new_data(filename):
def value_to_optimize(data):
data_set = np.genfromtxt(filename, delimiter=',',skip_header=1)
doe = data_set[:,:-1]
new_data_set = np.vstack((np.array(doe),np.array(data)))
return result_of_another_function(new_data_set)
rst = minimize(value_to_optimize,[0,0])
return rst.x