Created
March 28, 2018 15:19
-
-
Save devforfu/e0556ae5a471f28f3a3e4fad7795dd5f to your computer and use it in GitHub Desktop.
Generators example (1)
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
""" | |
Simple example shows usage of generators as coroutines accepting values from | |
outside and yield processed values to caller. | |
""" | |
import re | |
def get_loss(regex='^[\d\w]+(\d.\d+).hdf5$'): | |
""" | |
Checks if name of file with model weights matches regular expression and | |
returns numerical value of loss. | |
Otherwise, None is returned. | |
""" | |
reg = re.compile(regex) | |
while True: | |
filename = yield | |
match = reg.match(filename) | |
result = None if match is None else float(match.group(1)) | |
yield result | |
def apply(gen, item): | |
"""Advance generator to next yield statement and sends value.""" | |
gen.send(None) | |
result = gen.send(item) | |
return result | |
def main(): | |
filenames = [ | |
'model.h5', | |
'checkpoint', | |
'weights_1.042.hdf5', | |
'log.txt', | |
'weights_bs128_0.984.hdf5', | |
'weights_resnet_val_loss_0.209.hdf5' | |
] | |
gen = get_loss() | |
for filename in filenames: | |
result = apply(gen, filename) | |
if not result: | |
continue | |
print(result) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment