In numpy I can do the following to avoid division by zero:
a = np.random.randint(0, 10, 100)
b = np.random.randint(0, 10, 100)
c = np.zeros_like(a, dtype=np.float32) # It can be anything other than zero
c = np.divide(a, b, out=c, where=(b!=0))
In torch.divide there is nowhere argument for masking. Only way seems to be replacing inf with desired value after the division takes place. Is there any better way to do this in pytorch?
Would selecting the desired values in a and b before applying the division work?
E.g. you could create a mask first and use it to index both tensors where the condition would be b!=0.
Another solution is to use where before you divide (this avoids initialising c and then conditionally modifying its elements in-place - I think this looks more elegant, but I haven’t measured its efficiency):
good_inds = (b != 0)
fill_value = 42 # or whatever
c = (
torch.where(good_inds, a, fill_value) /
torch.where(good_inds, b, 1)
)