Python随机生成每个实例的种子

时间:2018-10-29 02:57:59

标签: python python-3.x

无论如何,我可以为每个类实例生成带有其自身种子的随机数。为了清楚说明这一点,以下是最少的代码。成功的结果将使前10位等于后10位。

import sys
import numpy as np

class DataGen:
    def __init__(self, seed):
        np.random.seed(seed)

    def generate(self):
        return np.random.uniform(0, 1, size=10)


a=DataGen(1)
print(a.generate())
print("another 10")
print(a.generate())


b=DataGen(1) 
print("another 10") 
print(a.generate()) #generate random numbers use a.
print("another 10")
print(b.generate()) #first time to use b. 

1 个答案:

答案 0 :(得分:3)

您应该使用RandomState

import numpy as np


class DataGen:
    def __init__(self, seed):
        self.state = np.random.RandomState(seed)

    def generate(self):
        return self.state.uniform(0, 1, size=10)


a = DataGen(1)
print(a.generate())
print("another 10")
print(a.generate())

b = DataGen(1)
print("another 10")
print(a.generate())  # generate random numbers use a.
print("another 10")
print(b.generate())  # first time to use b.

输出

[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01
 1.46755891e-01 9.23385948e-02 1.86260211e-01 3.45560727e-01
 3.96767474e-01 5.38816734e-01]
another 10
[0.41919451 0.6852195  0.20445225 0.87811744 0.02738759 0.67046751
 0.4173048  0.55868983 0.14038694 0.19810149]
another 10
[0.80074457 0.96826158 0.31342418 0.69232262 0.87638915 0.89460666
 0.08504421 0.03905478 0.16983042 0.8781425 ]
another 10
[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01
 1.46755891e-01 9.23385948e-02 1.86260211e-01 3.45560727e-01
 3.96767474e-01 5.38816734e-01]

进一步

  1. Difference between RandomState and seed in numpy