简体   繁体   中英

Modules and numpy.random seeds

I have two modules, the first of which is:

# module.py

import numpy
import myrandom

class A():
    def __init__(self,n1,n2):
        A.rng_set1 = myrandom.generate_random(n1)
        A.rng_set2 = myrandom.generate_random(n2)
        A.data = np.concatenate((A.rng_set1,A.rng_set2))

The module myrandom is something like:

# myrandom.py

import numpy as np

def generate_random(n):
    return np.random.rand(n)

Given a seed I want A.data to be predictable. I don't want rng_set1 and rng_set2 to share the same numbers if n1 equals n2 . I don't understand how to seed this thing.

I've tried putting np.random.seed(constant) into generate_random , into A 's init, at module.py top level and before import module.py . I can't seem to get the desired result.

How am i supposed to do this? Thank you.


EDIT:

An oversight from me was causing the unpredictable behaviour. Please see answer below.

You could change myrandom.py to:

# myrandom.py

import numpy as np

def generate_random(n):
    np.random.seed(n)
    return np.random.rand(n)

This makes the seed replicable and changes the output for different inputs.

Better:

def generate_random(n):
    rng = np.random.default_rng(seed=n)
    return rng.random.rand(n)

Based on numpy documentation numpy.random.rand() is a legacy function. Numpy suggests constructing a Generator with a seed, that can be used to generate numbers deterministically. As a convenience function, numpy.random.default_rng() can be used to create to simply create a generator:

from numpy import random

# seed can be a number that will ensure deterministic behaviour
generator_1 = random.default_rng(seed=1)
generator_1.integers(10, size=10)
# array([4, 5, 7, 9, 0, 1, 8, 9, 2, 3])

generator_2 = random.default_rng(seed=1)
generator_2.integers(10, size=10)
# array([4, 5, 7, 9, 0, 1, 8, 9, 2, 3])

There was an oversight here. The unpredictable behaviour I was encountering was due to mixing numpy.random and python's random library. Having only numpy.random to act within generate_random results in the expected behaviour when np.random.seed() is called before importing module or at top level of module or myrandom . Thank you all my friends for your time and helpfulness.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM