简体   繁体   中英

random.sample() how to control reproducibility

Is there a way to control random.sample()? I fix seed that standard way:

def seed_everything(seed=42):
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.backends.cudnn.deterministic = True
 
seed_everything(42)

Nevertheless the result of code below is different every time:

idxT=[0,1,2,3,4,5,6]
idxT = [
        idxT[j] for j in sorted(random.sample(range(len(idxT)), 3))
    ]
idxT

I think Ry is on the right track: if you want the return value of random.sample to be the same everytime it is called you will have to set random.seed to the same value prior to every invocation of random.sample .

Here are three simplified examples to illustrate:

random.seed(42)
idxT=[0,1,2,3,4,5,6]
for _ in range(2):
    for _ in range(3):
        print(random.sample(idxT, 3))
    print()

[5, 0, 6]
[5, 2, 1]
[1, 6, 0]

[5, 6, 4]
[0, 4, 3]
[0, 6, 5]
idxT=[0,1,2,3,4,5,6]
for _ in range(2):
    random.seed(42)
    for _ in range(3):
        print(random.sample(idxT, 3))
    print()

[5, 0, 6]
[5, 2, 1]
[1, 6, 0]

[5, 0, 6]
[5, 2, 1]
[1, 6, 0]
idxT=[0,1,2,3,4,5,6]
for _ in range(2):
    for _ in range(3):
        random.seed(42)
        print(random.sample(idxT, 3))
    print()

[5, 0, 6]
[5, 0, 6]
[5, 0, 6]

[5, 0, 6]
[5, 0, 6]
[5, 0, 6]

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