PyTorch, when divided by zero, set the result value with 0
In Pytorch, when values are divided by zero, replace the result value with 0, as it will output NaN. Here is an example,
a = th.from_numpy(np.array([ [1, 0], [0, 1], [1, 1]])) 
b = th.zeros_like(a)
b[0, :] = 2
a = a / b

How can I do that?

You can replace NaN values obtained after division with 0 using the following method -

Create a ByteTensor indicating the positions of NaN

a != a
&gt;&gt; tensor([[False, False],
        [ True, False],
        [False, False]])


Replace NaN values indicated by above Tensor with 0

a = a / b
&gt;&gt; tensor([[0.5000, 0.0000],
        [   nan,    inf],
        [   inf,    inf]])

a[a != a] = 0
&gt;&gt; tensor([[0.5000, 0.0000],
        [0.0000,    inf],
        [   inf,    inf]])

Note this will also replace any NaN values introduced before division.
