Reputation: 93
I'm new to Python and trying to automate finding optimum operating parameters of a savgol filter that feeds into PLS analysis. First, I had a prediction function calculate results and plot them.
To try and automate optimising, I have a for loop that goes over a range of numbers then feeds this number into t. I want the filter which then goes into the function. The aim is to find the smallest possible result after applying the function and return the arguments that gave rise to it.
I'm not sure how to do this. Also, I don't want the for loop to produce plot every single time. Do I just cut and paste the section of code that does this into the loop function?
def loopit():
for derivative in range(1,3):
for windowlength in range(5, 50, 2):
X2_calib = savgol_filter(X_calib, windowlength, polyorder = 4, deriv=derivative)
X2_valid = savgol_filter(X_valid, windowlength, polyorder = 4, deriv=derivative)
#invoking prediction function
prediction(X2_calib, Y_calib, X2_valid, Y_valid, plot_components=False)
difference = (abs((pd.DataFrame(Y_valid))-(pd.DataFrame(Y_pred))))/abs(pd.DataFrame(Y_valid))
sumOfDifference = difference.sum()
#minimum of all sum of prediction
minimum = min(sumOfDifference)
return (minimum)
Upvotes: 0
Views: 77
Reputation: 9945
If I get your problem right, you want to loop through bunch of hyper parameters and return not just the minimum that their iterations yielded but also the parameters which yielded it.
If you want your arguments i.e derivative
& windowlength
to be returned , just try
def loopit():
results = {}
_min = 100.0 # Or any other value which you think will be higher than all of the minimums
for derivative in range(1,3):
for windowlength in range(5, 50, 2):
.
.
.### Do Something
.
.
.
sumOfDifference = difference.sum()
if min(sumOfDifference) < _min:
results['minimum'] = min
results['derivative_val'] = derivative
results['windowlenghts_val'] = windowlength
_min = min(sumOfDifference)
return results
To call your function just do :
res = loopit()
print(res['minimum'])
print(res['derivative_val'])
print(res['windowlenghts_val'])
Upvotes: 1