How about:

    self.gradients = np.where(np.isnan(gradients), 0., gradients)

that way we avoid possible changing the user's input array.