Rockbar
Rockbar

Reputation: 1161

np.random.permutation with seed?

I want to use a seed with np.random.permutation, like

np.random.permutation(10, seed=42)

I get the following error:

"permutation() takes no keyword arguments"

How can I do that else? Thanks.

Upvotes: 32

Views: 27921

Answers (4)

Sebastian Mendez
Sebastian Mendez

Reputation: 2981

If you want it in one line, you can create a new RandomState, and call the permutation on that:

np.random.RandomState(seed=42).permutation(10)

This is better than just setting the seed of np.random, as it will have only a localized effect.

NumPy 1.16 Update:

RandomState is now considered a legacy feature. I see no indication that it will be deprecated any time soon, but now the recommended way to generate reproducible random numbers is via Random Generators, of which the default can be instantiated like so:

np.random.default_rng(seed=42).permutation(10)

Note that it appears like there's no guarantees of bitstream equivalence across different versions of NumPy for this generator, wheras for the RandomState the documentation states that "This generator is considered frozen and will have no further improvements. It is guaranteed to produce the same values as the final point release of NumPy v1.16."

Upvotes: 71

Giorgos Myrianthous
Giorgos Myrianthous

Reputation: 39840

np.random.seed(42)
np.random.permutation(10)

If you want to call np.random.permutation(10) multiple times and get identical results, you also need to call np.random.seed(42) every time you call permutation().


For instance,

np.random.seed(42)
print(np.random.permutation(10))
print(np.random.permutation(10))

will produce different results:

[8 1 5 0 7 2 9 4 3 6]
[0 1 8 5 3 4 7 9 6 2]

while

np.random.seed(42)
print(np.random.permutation(10))
np.random.seed(42)
print(np.random.permutation(10))

will give the same output:

[8 1 5 0 7 2 9 4 3 6]
[8 1 5 0 7 2 9 4 3 6]

Upvotes: 36

Danilo Pena
Danilo Pena

Reputation: 19

You can break it down into:

import numpy as np
np.random.seed(10)
np.random.permutation(10)

By initializing the random seed first, this will guarantee that you get the same permutation.

Upvotes: 1

James
James

Reputation: 36633

Set the seed in the previous line

np.random.seed(42)
np.random.permutation(10)

Upvotes: 4

Related Questions