简体   繁体   English

模块和 numpy.random 种子

[英]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类似于:

# 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.给定一个种子,我希望A.data是可预测的。 I don't want rng_set1 and rng_set2 to share the same numbers if n1 equals n2 .如果n1等于n2我不希望rng_set1rng_set2共享相同的数字。 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 .我试过将np.random.seed(constant)放入generate_random ,放入A的 init ,在module.py顶层和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更改为:

# 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.这使seed可复制并更改不同输入的输出。

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 文档numpy.random.rand()是一个遗留函数。 Numpy suggests constructing a Generator with a seed, that can be used to generate numbers deterministically. Numpy 建议用种子构建一个生成器,它可以用来确定性地生成数字。 As a convenience function, numpy.random.default_rng() can be used to create to simply create a generator:作为一个方便的函数, numpy.random.default_rng()可以用来创建简单地创建一个生成器:

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.我遇到的不可预测的行为是由于混合了numpy.random和 python 的random库。 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 .由于只有numpy.random内行事generate_random当预期的行为结果np.random.seed()导入之前被称为module或在顶层modulemyrandom Thank you all my friends for your time and helpfulness.感谢所有朋友的时间和帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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