-1

I am current following a tutorial in Pytorch and there is this expression:

grad_h[h < 0] = 0

How does this syntax work and what does it do?

7
  • before this q is shut, it is assigning all values in the grad_h array which are less than zero to zero Commented Aug 21, 2018 at 7:07
  • if grad_h is dict and h = 1 is int then: grad_h[h < 0] = 0 will result in grad_h = {False: 0} Commented Aug 21, 2018 at 7:07
  • This works because grad_h is a NumPy array. Commented Aug 21, 2018 at 7:08
  • 1
    This is almost certainly a duplicate of an existing question with a good answer; we just need to find it for you. Commented Aug 21, 2018 at 7:09
  • Meanwhile, here's the relevant section in the numpy user guide, which explains things pretty nicely. Commented Aug 21, 2018 at 7:12

2 Answers 2

0

It means replace with zeros all the values in grad_h where its corresponding h is negative.

So it is implementing some kind of mask, to keep the gradient values only when h is negative

suppose that grad_h and h have the same shape.

grad_h.shape == h.shape

when you do h < 0 you obtain an array of booleans of the same shape that is set to True if h[i] < 0 for each i.

So then you apply this mask to do slicing on grad_h and finally you set all the sliced elements to zero

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain how that syntax works? At a casual glance, I'd expect it to set the attribute True or False of grad_h to 0…
ok I'll edit to explain better
-2

It means that the variable grad_h is equal to 0 as long as h is less than 0.

1 Comment

kindly consider adding more information in your answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.