Skip to content

Commit 6142adb

Browse files
paulgc17tfx-copybara
authored andcommitted
Cast finite quantile boundaries to float64 to avoid precision errors.
PiperOrigin-RevId: 296235385
1 parent d9865e9 commit 6142adb

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

tensorflow_data_validation/utils/quantiles_util.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,13 @@ def generate_equi_width_buckets(quantiles: List[float],
238238
# the (+inf, +inf) buckets.
239239
last_bucket_count -= sample_count
240240

241+
# Cast finite boundaries from float32 to float64 to avoid precision errors.
242+
# This error can happen when both min and max in the boundaries are valid
243+
# float32 values, but when we compute (max-min) to compute the width it can
244+
# result in an overflow.
245+
# Example: min=-3.4e+38, max=3.4e+38
246+
finite_values = np.array(finite_values, dtype=np.float64)
247+
241248
# Check if the finite quantile boundaries are sorted.
242249
assert np.all(np.diff(finite_values) >= 0), (
243250
'Quantiles output not sorted %r' % ','.join(map(str, finite_values)))
@@ -262,7 +269,7 @@ def generate_equi_width_buckets(quantiles: List[float],
262269

263270

264271
def _generate_equi_width_buckets_from_finite_boundaries(
265-
quantiles: List[float], sample_count: float, num_buckets: int):
272+
quantiles: np.ndarray, sample_count: float, num_buckets: int):
266273
"""Generates equi width buckets from finite quantiles boundaries."""
267274

268275
def _compute_count(start_index, end_index, start_pos):

tensorflow_data_validation/utils/quantiles_util_test.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,22 @@ def test_find_median(self):
192192
quantiles_util.Bucket(2.33333333, 3.66666666, 1.33333333),
193193
quantiles_util.Bucket(3.66666666, 5, 2.33333333)],
194194
},
195+
{
196+
'testcase_name': 'finite_values_float_boundaries_float32_overflow',
197+
'quantiles': list(np.array(
198+
[-3.4e+38, 1.0, 2.0, 3.0, 4.0, 5.0, 3.4e+38], dtype=np.float32)),
199+
'finite_min': 1,
200+
'finite_max': 5,
201+
'total_count': 6,
202+
'num_buckets': 3,
203+
'expected_buckets': [
204+
quantiles_util.Bucket(
205+
-3.3999999521443642e+38, -1.1333333173814546e+38, 0.66666666),
206+
quantiles_util.Bucket(
207+
-1.1333333173814546e+38, 1.133333317381455e+38, 4.66666666),
208+
quantiles_util.Bucket(
209+
1.133333317381455e+38, 3.3999999521443642e+38, 0.66666666)],
210+
},
195211
{
196212
'testcase_name': 'same_min_max',
197213
'quantiles': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],

0 commit comments

Comments
 (0)