-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
14 changed files
with
885 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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 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
50 changes: 50 additions & 0 deletions
50
yggdrasil_decision_forests/port/python/ydf/dataset/io/generator.py
This file contains 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,50 @@ | ||
# Copyright 2022 Google LLC. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Utility to handle datasets.""" | ||
|
||
import abc | ||
from typing import Dict, Iterator, Optional | ||
import numpy as np | ||
|
||
# A single batch of data in various formats. The attribute values are indexed by | ||
# attribute names. | ||
NumpyExampleBatch = Dict[str, np.ndarray] | ||
|
||
|
||
class BatchedExampleGenerator(abc.ABC): | ||
"""A class able to generate batches of examples.""" | ||
|
||
def __init__(self, num_examples: Optional[int]): | ||
self._num_examples = num_examples | ||
|
||
@property | ||
def num_examples(self) -> Optional[int]: | ||
"""Number of examples in the dataset.""" | ||
return self._num_examples | ||
|
||
def num_batches(self, batch_size: int) -> Optional[int]: | ||
if self._num_examples is None: | ||
return None | ||
return (self._num_examples + batch_size - 1) // batch_size | ||
|
||
@abc.abstractmethod | ||
def generate( | ||
self, | ||
batch_size: int, | ||
shuffle: bool, | ||
seed: Optional[int] = None, | ||
) -> Iterator[NumpyExampleBatch]: | ||
"""Generate an iterator.""" | ||
raise NotImplementedError |
54 changes: 54 additions & 0 deletions
54
yggdrasil_decision_forests/port/python/ydf/dataset/io/numpy_io.py
This file contains 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,54 @@ | ||
# Copyright 2022 Google LLC. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Dataset generator for dict of numpy arrays.""" | ||
|
||
from typing import Dict, Iterator, Optional | ||
import numpy as np | ||
from ydf.dataset.io import generator as generator_lib | ||
|
||
|
||
class NumpyDictBatchedExampleGenerator(generator_lib.BatchedExampleGenerator): | ||
"""Class to consume dictionaries of Numpy arrays.""" | ||
|
||
def __init__(self, data: Dict[str, np.ndarray]): | ||
self._data = data | ||
super().__init__(num_examples=len(next(iter(data.values())))) | ||
|
||
def generate( | ||
self, | ||
batch_size: int, | ||
shuffle: bool, | ||
seed: Optional[int] = None, | ||
) -> Iterator[generator_lib.NumpyExampleBatch]: | ||
assert self._num_examples is not None | ||
if not shuffle: | ||
i = 0 | ||
while i < self._num_examples: | ||
begin_idx = i | ||
end_idx = min(i + batch_size, self._num_examples) | ||
yield {str(k): v[begin_idx:end_idx] for k, v in self._data.items()} | ||
i += batch_size | ||
else: | ||
if seed is None: | ||
raise ValueError("seed is required if shuffle=True") | ||
rng = np.random.default_rng(seed) | ||
idxs = rng.permutation(self._num_examples) | ||
i = 0 | ||
while i < self._num_examples: | ||
begin_idx = i | ||
end_idx = min(i + batch_size, self._num_examples) | ||
selected_idxs = idxs[begin_idx:end_idx] | ||
yield {str(k): v[selected_idxs] for k, v in self._data.items()} | ||
i += batch_size |
69 changes: 69 additions & 0 deletions
69
yggdrasil_decision_forests/port/python/ydf/dataset/io/numpy_io_test.py
This file contains 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,69 @@ | ||
# Copyright 2022 Google LLC. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Test dataspec utilities for pandas.""" | ||
|
||
from absl.testing import absltest | ||
import numpy as np | ||
|
||
from ydf.dataset.io import numpy_io | ||
from ydf.utils import test_utils | ||
|
||
|
||
class NumpyIOTest(absltest.TestCase): | ||
|
||
def test_numpy_generator(self): | ||
ds = numpy_io.NumpyDictBatchedExampleGenerator({ | ||
"a": np.array([1, 2, 3]), | ||
"b": np.array(["x", "y", "z"]), | ||
}) | ||
|
||
for batch_idx, batch in enumerate(ds.generate(batch_size=2, shuffle=False)): | ||
if batch_idx == 0: | ||
test_utils.assert_almost_equal( | ||
batch, {"a": np.array([1, 2]), "b": np.array(["x", "y"])} | ||
) | ||
elif batch_idx == 1: | ||
test_utils.assert_almost_equal( | ||
batch, {"a": np.array([3]), "b": np.array(["z"])} | ||
) | ||
else: | ||
assert False | ||
|
||
def test_numpy_generator_shuffle(self): | ||
ds = numpy_io.NumpyDictBatchedExampleGenerator({ | ||
"a": np.array([1, 2, 3]), | ||
"b": np.array(["x", "y", "z"]), | ||
}) | ||
count_per_first_a_value = [0] * 4 | ||
num_runs = 100 | ||
for i in range(100): | ||
num_sum_a = 0 | ||
num_batches = 0 | ||
for batch_idx, batch in enumerate( | ||
ds.generate(batch_size=2, shuffle=True, seed=i) | ||
): | ||
num_sum_a += np.sum(batch["a"]) | ||
num_batches += 1 | ||
if batch_idx == 0: | ||
first_value = batch["a"][0] | ||
count_per_first_a_value[first_value] += 1 | ||
self.assertEqual(num_batches, 2) | ||
self.assertEqual(num_sum_a, 1 + 2 + 3) | ||
for i in range(1, 3): | ||
self.assertGreater(count_per_first_a_value[i], num_runs / 10) | ||
|
||
|
||
if __name__ == "__main__": | ||
absltest.main() |
This file contains 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.