Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shuffle vs permute numpy

What is the difference between numpy.random.shuffle(x) and numpy.random.permutation(x)?

I have read the doc pages but I could not understand if there was any difference between the two when I just want to randomly shuffle the elements of an array.

To be more precise suppose I have an array x=[1,4,2,8].

If I want to generate random permutations of x, then what is the difference between shuffle(x) and permutation(x)?

like image 392
DotPi Avatar asked Mar 18 '13 10:03

DotPi


People also ask

What is the difference between shuffle and permutation?

That is, the permutation is a group element and the shuffle is the result of its action on a particular word.

How does Numpy shuffle work?

Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same.

What is Numpy random permutation?

numpy.random. permutation (x) Randomly permute a sequence, or return a permuted range. If x is a multi-dimensional array, it is only shuffled along its first index.

How do I shuffle rows in Numpy?

You can use numpy. random. shuffle() . This function only shuffles the array along the first axis of a multi-dimensional array.


1 Answers

np.random.permutation has two differences from np.random.shuffle:

  • if passed an array, it will return a shuffled copy of the array; np.random.shuffle shuffles the array inplace
  • if passed an integer, it will return a shuffled range i.e. np.random.shuffle(np.arange(n))

If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and shuffle the elements randomly.

The source code might help to understand this:

3280        def permutation(self, object x): ... 3307            if isinstance(x, (int, np.integer)): 3308                arr = np.arange(x) 3309            else: 3310                arr = np.array(x) 3311            self.shuffle(arr) 3312            return arr 
like image 100
ecatmur Avatar answered Oct 22 '22 07:10

ecatmur