The difference in roles between shuffle and permutation in Python's No.Fi

Asked 2 years ago, Updated 2 years ago, 56 views

The role of shuffle and permutation in Python nupi is to mix arrays randomly But I wonder what the difference is between the two.

python numpy

2022-09-22 19:09

1 Answers

In fact, permutation returns one of the permutations, but the result of shuffle is one of the permutations anyway, so the result itself is the same.

As per the permutation help (https://het.as.utexas.edu/HET/Software/Numpy/reference/generated/numpy.random.permutation.html), the important difference is that permutation copies the array and returns it. So the original is retained. On the other hand, shuffle changes the original.

If numpy is coded as cyton (.pyx) and you see the actual code, copy the array and call shuffle.

def permutation(self, object x):
        if isinstance(x, (int, np.integer)):
            arr = np.arange(x)
            self.shuffle(arr)
            return arr

        arr = np.asarray(x)

        # # shuffle has fast-path for 1-d
        if arr.ndim == 1:
            # # Return a copy if same memory
            if np.may_share_memory(arr, x):
                arr = np.array(arr)
            self.shuffle(arr)
            return arr

        # # Shuffle index array, dtype to ensure fast path
        idx = np.arange(arr.shape[0], dtype=np.intp)
        self.shuffle(idx)
        return arr[idx]
In [6]: ARR = [1, 2, 3]                                                         

In [7]: np.random.permutation(ARR)                                              
Out[7]: array([1, 3, 2])

In [8]: ARR                                                                     
Out[8]: [1, 2, 3]

In [9]: np.random.shuffle(ARR)                                                  

In [10]: ARR                                                                    
Out[10]: [1, 3, 2]


2022-09-22 19:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.