Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

python - 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
question from:https://stackoverflow.com/questions/65649821/random-sample-how-to-control-reproducibility

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...