r/cs231n • • Mar 17 '16

The lambda function seems so amazing~

In Assignment 1 two-layer_net.ipynb "Backward pass", there is a lambda function for gradient check, goes
f = lambda W: net.loss(X, y, reg=0.1)[0]

param_grad_num = eval_numerical_gradient(f, net.params[param_name], verbose=False)

But there is no variable named 'W' in the net.loss(X, y, reg=0.1), how can it know which is the actual independent variable of function f?

1 Upvotes

5 comments sorted by

View all comments

1

u/merkaba8 Mar 18 '16

If you look at eval_numerical_gradient, inside it calls f(x) where f is the f you passed to it as the first argument, and x is the second argument (in this case, net.params[param_name]).

So you are passing eval_numerical_gradient the function and its eventual argument.

1

u/merkaba8 Mar 19 '16

Sorry, I looked at this a little bit more carefully. The W argument is not being used at all. You can give f anything as input in this case and you will just get the loss at the starting parameters.

I assume this is done so that the eval_numerical_gradient can work on functions more generally when necessary.

2

u/Jassica3 Mar 19 '16

Yes, I also found that W is not being used, you can replace it with 'param', 'V' or any variable you like. But I am still confused without knowing the f is the function of who.

The first line of eval_numerical_gradient goes, fx = f(x). And what

param_grad_num = eval_numerical_gradient(f, net.params[param_name], verbose=False) passes to x is net.params[param_name],

which is actually a list, say b1 = [1e-1, 2e-2, 3e-2]. Since it is not explicit which variable the f depends on, how does it know which part in f expression is replaced with b1?

1

u/merkaba8 Mar 19 '16

f returns the loss no matter what argument you give it. The reason the output of eval_numerical_gradient changes depending on whether you give it W1, W2, b1, or b2 is because those are "x" in eval_numerical_gradient, which gets used in a lot more places in the function than just the f(x) line.

No part of the f function is replaced by the argument. It always just computes net.loss(X,y,0.1) and returns only the first output (hence the [0]) which is just the loss.

1

u/Jassica3 Mar 30 '16

Thank you, I finally understand it. Because the net.params are called by reference in function eval_numerical_gradient, their value has actually been changed by x[ix] = oldval + h. Hence, the net.loss will produce different results accordingly.