Repository navigation
fix: treat a float NaN as absent, the same as None (#367) #381
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| """A float NaN is absent, the same as ``None`` (#367). | ||
|
|
||
| NaN is how pandas and numpy spell a missing number. Read as a value it scored | ||
| two identical NaNs 0.0, because NaN equals nothing under IEEE 754. Read as | ||
| absent it takes ``None``'s place in every confusion-matrix cell. | ||
| """ | ||
|
|
||
| from decimal import Decimal | ||
| from typing import List, Optional | ||
|
|
||
| import numpy as np | ||
| import pytest | ||
|
|
||
| from stickler.comparators.levenshtein import LevenshteinComparator | ||
| from stickler.comparators.numeric import NumericComparator | ||
| from stickler.structured_object_evaluator.models.comparable_field import ComparableField | ||
| from stickler.structured_object_evaluator.models.field_helper import FieldHelper | ||
| from stickler.structured_object_evaluator.models.null_helper import NullHelper | ||
| from stickler.structured_object_evaluator.models.structured_model import StructuredModel | ||
|
|
||
| NAN = float("nan") | ||
|
|
||
|
|
||
| class Reading(StructuredModel): | ||
| value: Optional[float] = ComparableField( | ||
| comparator=NumericComparator(relative_tolerance=0.001), default=None | ||
| ) | ||
|
|
||
|
|
||
| class Item(StructuredModel): | ||
| sku: str = ComparableField(comparator=LevenshteinComparator(), default="a") | ||
| value: Optional[float] = ComparableField( | ||
| comparator=NumericComparator(), default=None | ||
| ) | ||
|
|
||
|
|
||
| class Order(StructuredModel): | ||
| items: Optional[List[Item]] = ComparableField(default=None) | ||
|
|
||
|
|
||
| def _counts(gt, pred): | ||
| result = Reading(value=gt).compare_with( | ||
| Reading(value=pred), include_confusion_matrix=True | ||
| ) | ||
| overall = result["confusion_matrix"]["fields"]["value"]["overall"] | ||
| counts = {k: overall[k] for k in ("tp", "tn", "fa", "fd", "fn") if overall[k]} | ||
| return result["field_scores"]["value"], counts | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "gt, pred, score, counts", | ||
| [ | ||
| (NAN, NAN, 1.0, {"tn": 1}), | ||
| (NAN, None, 1.0, {"tn": 1}), | ||
| (None, NAN, 1.0, {"tn": 1}), | ||
| (NAN, 5.0, 0.0, {"fa": 1}), | ||
| (5.0, NAN, 0.0, {"fn": 1}), | ||
| ], | ||
| ) | ||
| def test_nan_classifies_like_none(gt, pred, score, counts): | ||
| assert _counts(gt, pred) == (score, counts) | ||
|
|
||
|
|
||
| def test_numpy_nan_is_absent(): | ||
| assert _counts(np.float64("nan"), np.float64("nan")) == (1.0, {"tn": 1}) | ||
|
|
||
|
|
||
| def test_comparator_reads_nan_as_missing(): | ||
| cmp = NumericComparator(relative_tolerance=0.001) | ||
| assert cmp.compare(NAN, NAN) == 1.0 | ||
| assert cmp.compare(NAN, None) == 1.0 | ||
| assert cmp.compare(NAN, 1.0) == 0.0 | ||
| assert cmp.compare(1.0, NAN) == 0.0 | ||
|
|
||
|
|
||
| def test_decimal_nan_is_still_a_non_match(): | ||
| # Only a float NaN is absent; a Decimal NaN still reaches the guard. | ||
| assert NumericComparator().compare(Decimal("NaN"), Decimal("NaN")) == 0.0 | ||
|
|
||
|
|
||
| def test_nan_in_a_list_element_field_is_absent(): | ||
| gt = Order(items=[Item(sku="a", value=NAN)]) | ||
| pred = Order(items=[Item(sku="a", value=NAN)]) | ||
| result = gt.compare_with(pred, include_confusion_matrix=True) | ||
|
|
||
| assert result["field_scores"]["items"] == 1.0 | ||
| leaf = result["confusion_matrix"]["fields"]["items"]["fields"]["value"] | ||
| assert leaf["overall"]["tn"] == 1 | ||
| assert leaf["overall"]["fd"] == 0 | ||
|
|
||
|
|
||
| def test_null_predicates_agree_on_nan(): | ||
| assert NullHelper.is_nan(NAN) | ||
| assert not NullHelper.is_nan(0.0) | ||
| assert not NullHelper.is_nan("nan") | ||
| assert NullHelper.is_effectively_null_for_primitives(NAN) | ||
| assert FieldHelper.is_null_value(NAN) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Non-blocking, and you already documented this at L40 ("including
numpy.float64"),so this is a question about intent rather than a defect.
isinstance(val, float)catches a Python float andnp.float64(a float subclass),but not
np.float32,np.float16, ornp.longdouble. Measured:1479c3d46a259d80NumericComparator().compare(v, v), py-float / float64 NaNnp.float32/np.float16NaNSo the same missing value scores differently by dtype width, where the baseline was
uniformly 0.0.
Two things keep this low rather than blocking, and I want to be straight about both:
The normal path is fine. On a field annotated
Optional[float], pydantic coercesevery numpy width to a Python float, so all four widths score
1.0with a truenegative on your branch (all
0.0with a false discovery ondev). A pandas float32column bound to a typed float field is fully fixed. The split is only reachable via a
direct comparator call or a field annotated
Any.And the unfixed widths sit exactly at the old behaviour, so this is an incomplete fix
rather than a regression. Nothing got worse.
The part I think is worth acting on regardless:
test_numpy_nan_is_absentexercisesnp.float64through a typedOptional[float]field, so pydantic coercion carries it— the test would pass identically with no numpy handling at all. It doesn't currently
pin the numpy support it's named for. A case going through a direct comparator call or
an
Anyfield would.If you do want to widen it, concrete types read better here than an ABC:
That needs an
import numpy as npat the top — this module currently imports onlymathandtyping, which is why I'm not leaving it as a one-click suggestion.I tried
numbers.Realfirst and talked myself out of it: it admitsint,boolandFraction, which can never be NaN, so a reader of a function namedis_nanhas towork out why integers are in scope — and it still excludes
Decimal('NaN'), sinceDecimalisn't registered asnumbers.Real. It looks more general than it is, whichis worse to maintain than your explicit float64-only scope. (Cost is not the reason:
I measured ~184ns vs ~38ns per call, which is nothing at field-per-case volume.)
Equally fine to declare float64-only the intended scope and just tighten the test. The
test gap is the part I'd act on; the predicate is your call.
Measured on two isolated clones, baseline
dev@1479c3d4and this PR @6a259d80,each importing its own tree —
__version__is1.0.0on both, so I keyed offhasattr(NullHelper, 'is_nan')instead.