Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

python - Reset numpy random generator instance

I need independent random generator instances with the ability to reset.

For Python's built-in random generator I wrote the following class which is enough for my needs (if you have a better implementation, let me know):

from random import Random

class PyPRNG(Random):

    def __init__(self, seed=None):
        super().__init__(seed)
        self._state = self.getstate()

    def reset(self):
        self.setstate(self._state)

>>> a = PyPRNG(2021)
>>> a.random()
0.8363375023320742
>>> a.random()
0.8583024042081875
>>> a.reset()
>>> a.random()
0.8363375023320742

Now, I want to play with numpy's PRNG.

I am not sure about how to implement reset. SeedSequence was not so clear for me. Finally I did this:

from numpy.random import Generator, MT19937, PCG64, Philox, SFC64

class NumpyPRNG(Generator):

    def __init__(self, seed=None, bit_generator=MT19937):
        _bit_generator = bit_generator(seed)
        self._state = _bit_generator.state
        super().__init__(_bit_generator)

    def reset(self):
        self.bit_generator.state = self._state.copy()

>>> b = NumpyPRNG(2021, Philox)
>>> b.random()
0.2934718429185965
>>> b.random()
0.6752607814067463
>>> b.reset()
>>> b.random
0.2934718429185965

It works, but maybe you can point me to a better solution... ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...