파이썬 넘파이에서 shuffle와 permutation의 역할차이
조회수 4538회
1 답변
-
사실 permutation 은 순열중에 하나를 리턴하는 것인데 어차피 shuffle 의 결과는 순열중에 하나이기 때문에 결과 자체는 같다고 할 수 있습니다.
permutation 도움말(https://het.as.utexas.edu/HET/Software/Numpy/reference/generated/numpy.random.permutation.html ) 대로 중요한 차이점은 permutation 은 array를 복사하여 리턴한다는 것 입니다. 즉 원본은 유지가 됩니다. 반면에 shffle 은 원본을 바꿉니다.
numpy 가 cython으로 코딩(.pyx)되어 있는데 실제 코드를 보면 배열을 복사후 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]
댓글 입력