Skip to content

Adding equivalent to numpy.nan_to_num functionality #540

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from

Conversation

aspeers
Copy link

@aspeers aspeers commented Dec 8, 2023

Adding equivalent to numpy.nan_to_num functionality
(https://numpy.org/doc/stable/reference/generated/numpy.nan_to_num.html)
addressing issue 479 (#479).

Motivation for these changes

Requested in issue #479

Implementation details

Added nan_to_num in pytensor/tensor/math.py

Checklist

Major / Breaking Changes

  • ...

New features

  • added nan_to_num

Bugfixes

  • ...

Documentation

Example:

import pytensor
from pytensor import tensor as pt

import numpy as np

# Replace NaN
print("Replace NaN")
x = pt.dvector("x")
y = pt.log(x)

f = pytensor.function([x], y)

t = np.random.normal(size=(10,))
print("x")
print(t)
print("f = log(x)")
print(f (t))

# Test: NaN default replacement
print("\nTest: NaN default replacement")
y1 = pt.math.nan_to_num(y)
f = pytensor.function([x], y1)
print(f (t))

# Test: NaN custom replacement
print("\nTest: NaN custom replacement")
y2 = pt.math.nan_to_num(y, nan=1)
f = pytensor.function([x], y2)
print(f (t))

# Replace +INF/-INF
print("\n\nReplace +INF/-INF")
a = pt.dvector("a")
b = pt.dvector("b")
c = pt.math.true_div(a,b)

t_a = np.random.normal(size=(10,))
t_b = np.zeros((10,))

f = pytensor.function([a, b], c)
print("a")
print(t_a)
print("b")
print(t_b)
print("f = a/b")
print(f(t_a, t_b))

# Test: +INF/-INF default replacement
c1 = pt.math.nan_to_num(c)
f = pytensor.function([a, b], c1)
print("\nTest: +INF/-INF default replacement")
print(f(t_a, t_b))

# Test: +INF/-INF custom replacement
c2 = pt.math.nan_to_num(c, posinf=5, neginf=-5)
f = pytensor.function([a, b], c2)
print("\nTest: +INF/-INF custom replacement")
print(f(t_a, t_b))

Maintenance

  • ...

@aspeers
Copy link
Author

aspeers commented Dec 8, 2023

First PR from yesterday's code sprint. Main reasons for marking as in progress included:

  • Had some difficulty running pytest locally. Resulted in multiple failures (most involving missing files/config parameters) which I figured the community could help by providing the relevant pytest command to run.
  • Could use advice on adding unit tests for the addition.
  • Was suggested to use ifelse() by @jessegrabowski instead of traditional if statements. ifelse is currently not imported/used in the math.py file and adding it to the imports list was causing a circular reference. Any thoughts would be welcomed!

Copy link
Member

@ricardoV94 ricardoV94 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for opening the PR. Looks great!

I left some small technical suggestions. We will also need some tests

Comment on lines +2984 to +2985
x = switch(bitwise_and(isinf(x), pos), maxf, x)
x = switch(bitwise_and(isinf(x), ~pos), minf, x)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's compare directly with posinf and neginf, if we don't have a isposinf and isneginf it's a good time to add it.

Suggested change
x = switch(bitwise_and(isinf(x), pos), maxf, x)
x = switch(bitwise_and(isinf(x), ~pos), minf, x)
x = switch(bitwise_and(isinf(x), pos), maxf, x)
x = switch(bitwise_and(isinf(x), ~pos), minf, x)

Comment on lines +2972 to +2974
# Get max and min values representable by x.dtype
maxf = np.finfo(x.real.dtype).max
minf = np.finfo(x.real.dtype).min
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's define it only when posinf and neginf are None

@@ -2937,7 +2937,58 @@ def matmul(x1: "ArrayLike", x2: "ArrayLike", dtype: Optional["DTypeLike"] = None
return out


def nan_to_num(x, nan=0.0, posinf=None, neginf=None):
"""
Replace NaN values with the `nan` keyword, +INF with the `posinf`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's just copy Numpy docstring. No point in reinventing it

"""

# Replace NaN's with nan keyword
x = switch(isnan(x), nan, x)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of overriding x, let's write all the checks isnan`isposinf\isneginf` on the original array.

@ricardoV94
Copy link
Member

ifelse is not appropriate because it requires a scalar condition, and here we want to work with arbitrary tensors

@ricardoV94 ricardoV94 added enhancement New feature or request NumPy compatibility labels Dec 9, 2023
@Dhruvanshu-Joshi
Copy link
Member

Hi @aspeers , are you still working on this?

@Dhruvanshu-Joshi Dhruvanshu-Joshi mentioned this pull request Jun 1, 2024
11 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants