-3

So I have this function here, can anyone explain what is going on here? I know whats happening in the body of the function, but not how lambda functions work I am new to lambda functions, so I am not sure how or what the function is returning. what exactly are t and c?

def get_gradient(self, A, b, x, beta):
    return (lambda t,c: (2*self.lambda_*x - A.T@(b*t)/c, sum(-b*t)/c))(1/(1+np.exp(b*(A@x+beta))), A.shape[0]

A is a matrix, b and x are column vectors and beta and lambda_ are scalars

Coder
  • 151
  • 2
  • 12
  • 1
    A lambda *expression* is just an expression that creates a function. There's no such thing as a lambda function distinct from functions created by a `def` statement. – chepner Nov 21 '19 at 23:42

2 Answers2

2

Here, get_gradient(self, A, b, x, beta) returns a function. In other words, it's a function that will define another function and return it as its output. It's useful if you want to define many functions depending on different type of arguments.

I'll refer you to this post to have more information on lambda functions and their typical uses.

But in your case, a simpler example may help you understand what's going on! Suppose that you have:

def f(a):
    return lambda x: x**a

Here, f returns a function that will apply the power of a to its input.

Once you have this, you can do:

g = f(2)

Which results in essentially the same as if you had done:

def g(x):
    return x**2

In either case, you can now do:

g(5)

# > 25
bglbrt
  • 2,018
  • 8
  • 21
  • what exactly is t and c in my case? – Coder Nov 21 '19 at 23:36
  • 2
    @SharhadBashar, they're just arguments that get passed into the function that's being returned. Like `x` in the example here. – ChrisGPT was on strike Nov 21 '19 at 23:37
  • Indeed. As @Chris said, ```t``` and ```c``` are arguments of the function that will be returned by the first function ```get_gradient()```. In other words, they will come to use and need to be specified once you use the function that has been returned by ```get_gradient()```. – bglbrt Nov 21 '19 at 23:40
  • ok I think i understood it now t = 1/(1+np.exp(b*(A@x+beta)) and c = A.shape[0] – Coder Nov 21 '19 at 23:41
2

looks like you're missing a final closing bracket there, so I think it should be:

def get_gradient(self, A, b, x, beta):
    return (lambda t,c: (2*self.lambda_*x - A.T@(b*t)/c, sum(-b*t)/c))(1/(1+np.exp(b*(A@x+beta))), A.shape[0])

which is the same as doing:

def get_gradient(self, A, b, x, beta):
    def fn(t, c):
        return (2*self.lambda_*x - A.T@(b*t)/c, sum(-b*t)/c))
    return fn(1/(1+np.exp(b*(A@x+beta))), A.shape[0])

which is the same as:

def get_gradient(self, A, b, x, beta):
    t = 1/(1+np.exp(b*(A@x+beta)))
    c = A.shape[0]
    return (2*self.lambda_*x - A.T@(b*t)/c, sum(-b*t)/c))
Sam Mason
  • 15,216
  • 1
  • 41
  • 60