-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Updated batch iterator implementation
- Loading branch information
Showing
3 changed files
with
33 additions
and
9 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,32 @@ | ||
class BatchIterator: | ||
|
||
def __init__(self, lst, batch_size): | ||
assert(isinstance(lst, list)) | ||
def __init__(self, data_iter, batch_size, end_value=None): | ||
assert(isinstance(batch_size, int) and batch_size > 0) | ||
self.__lst = lst | ||
assert(callable(end_value) or end_value is None) | ||
self.__data_iter = data_iter | ||
self.__index = 0 | ||
self.__batch_size = batch_size | ||
self.__end_value = end_value | ||
|
||
def __iter__(self): | ||
return self | ||
|
||
def __next__(self): | ||
if self.__index < len(self.__lst): | ||
batch = self.__lst[self.__index:self.__index + self.__batch_size] | ||
self.__index += self.__batch_size | ||
return batch | ||
else: | ||
buffer = [] | ||
while True: | ||
try: | ||
data = next(self.__data_iter) | ||
except StopIteration: | ||
break | ||
buffer.append(data) | ||
if len(buffer) == self.__batch_size: | ||
break | ||
|
||
if len(buffer) > 0: | ||
self.__index += 1 | ||
return buffer | ||
|
||
if self.__end_value is None: | ||
raise StopIteration | ||
else: | ||
return self.__end_value() |
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,11 @@ | ||
import unittest | ||
|
||
from arekit.common.pipeline.utils import BatchIterator | ||
|
||
|
||
class TestBalancing(unittest.TestCase): | ||
|
||
def test(self): | ||
batch_it = BatchIterator(data_iter=iter(range(10)), batch_size=3) | ||
for a in batch_it: | ||
print(a) |