drbombe
drbombe

Reputation: 639

Python random generation with seed for each instance

Is there anyway that I can generate random numbers with its own seed for each class instance. To make this point clear, the following is a minimal codes. Successful results will make the first 10 digits equal to the last 10 digits.

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. 

Upvotes: 1

Views: 498

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You should use 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.

Output

[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]

Further

  1. Difference between RandomState and seed in numpy

Upvotes: 5

Related Questions