I am trying to teach myself Python by working on some of the problems I am facing, and I need help understanding how to pass functions.
Let's say I'm trying to predict tomorrow a temperature based on today's and yesterdayโs temperatures, and I wrote the following function:
def predict_temp(temp_today, temp_yest, k1, k2): return k1*temp_today + k2*temp_yest
And I also wrote an error function to compare the list of predicted temperatures with actual temperatures and return the average absolute error:
def mean_abs_error(predictions, expected): return sum([abs(x - y) for (x,y) in zip(predictions,expected)]) / float(len(predictions))
Now, if I have a list of daytime temperatures for a certain interval in the past, I can see how my prediction function would do with specific parameters k1 and k2 as follows:
>>> past_temps = [41, 35, 37, 42, 48, 30, 39, 42, 33] >>> pred_temps = [predict_temp(past_temps[i-1],past_temps[i-2],0.5,0.5) for i in xrange(2,len(past_temps))] >>> print pred_temps [38.0, 36.0, 39.5, 45.0, 39.0, 34.5, 40.5] >>> print mean_abs_error(pred_temps, past_temps[2:]) 6.5
But how can I create a function to minimize my parameters k1 and k2 of my prec_temp function, taking into account the error function and my past_temps data?
In particular, I would like to write a minim (args *) function that takes a prediction function, an error function, some training data and uses a search / optimization method (for example, gradient descent) to estimate and return values โโfrom k1 and k2 that minimize my error given data?
I do not ask how to implement the optimization method. Suppose I can do this. Rather, I just wanted to know how to transfer my prediction and error functions (and my data) to my minimization function, and how to tell my minimization function that it should optimize the parameters k1 and k2 so that my minimization function can automatically search many different k1 and k2 settings, applying my prediction function with these parameters each time to data and computational error (for example, I did it manually for k1 = 0.5 and k2 = 0.5 above), and then return the best results.
I would like to be able to transfer these functions so that I can easily switch with various forecasting and error functions (differing not only in parameter settings). Each prediction function may have a different number of free parameters.
My minimization function should look something like this, but I don't know how to do it:
def minimize(prediction_function, which_args_to_optimize, error_function, data):
Edit: Is it that simple ?? This is not fun. I am returning to Java.
In a more serious note, I think I was also hung on how to use different forecasting functions with a different number of parameters for tuning. If I just take all the free parameters as a single tuple, I can save the form of the function in the same way that it can be easily transferred and used.