sachinruk
sachinruk

Reputation: 9869

list of functions with parameters

I need to obtain a list of functions, where my function is defined as follows:

import theano.tensor as tt

def tilted_loss(y,f,q):
    e = (y-f)
    return q*tt.sum(e)-tt.sum(e[e<0])

I attempted to do

qs = np.arange(0.05,1,0.05)
q_loss_f = [tilted_loss(q=q) for q in qs]

however, get the error TypeError: tilted_loss() missing 2 required positional arguments: 'y' and 'f'. I attempted the simpler a = tilted_loss(q=0.05) with the same result.

How do you go about creating this list of functions when parameters are required? Similar questions on SO consider the case where parameters are not involved.

Upvotes: 2

Views: 101

Answers (2)

Hang Guan
Hang Guan

Reputation: 102

There are 2 ways you can solve this problem. Both ways require you know the default values for y and f.

With the current function, there's simply no way for the Python interpreter to know the value of y and f when you call tilted_loss(q=0.05). y and f are simply undefined & unknown.

Solution (1): Add default values

We can fix this by adding default values for the function, for example, if default values are: y = 0, f = 1:

def tilted_loss(q, y=0, f=1):
    # original code goes here

Note that arguments with default values have to come AFTER non-default arguments (i.e q).

Solution (2): Specify default values during function call

Alternatively, just specify the default values every time you call that function. (Solution 1 is better)

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43136

You can use functools.partial:

q_loss_f = [functools.partial(tilted_loss, q=q) for q in qs]

Upvotes: 3

Related Questions