내맘대로 공부기록.

[ Python ]

[Python] numpy.ndarray.T 사용 해보기.

fwanggus 2023. 5. 2. 16:57

numpy ndarray의 행과 열의 인덱스를 상호 변경 하는  T 메서드를 사용해 본다.

 

예를 위해 다음의 array 의 준비한다.

사용 방법은 대상 어레이에 .T 만 붙여주면 된다.

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
# array([[1, 2, 3],
#        [4, 5, 6],
#        [7, 8, 9]])

a_T = a.T
#array([[1, 4, 7],
#       [2, 5, 8],
#       [3, 6, 9]])

 

이론적으로 내가 이해한  T의 작업을 설명하자면, 다음과 같다.

  • 행(row), 열(column) 인덱스를 상호 변경
  • 어레이 A를 정의했다고 가정하면, (T 호출) ➡️ Aij = Aji (이 수식으로 이해)로 표현할 수 있다.

 

사용한 Usecase

  • 이진화된 이미지의 마스킹 데이터를 String 형태로 변환해야 하는 경우에 사용할 수 있었으며,
  • 마스킹 픽셀 데이터를 Fortran-like index order로 취급해야 할 경우 T를 사용할 경우가 생긴다.
  • 캐글 컴페티션 제출 형식(Encoded Pixels)으로 RLE(Run-Lengh-Encoding) 포맷의 Fortran-like 인덱싱 형태를 요구하는 경우가 있기 때문에, 알아두면 유용하게 활용할 수 있다.

 

EncodedPixels
In order to reduce the submission file size, our metric uses run-length encoding on the pixel values. Instead of submitting an exhaustive list of indices for your segmentation, you will submit pairs of values that contain a start position and a run length. E.g. '1 3' implies starting at pixel 1 and running a total of 3 pixels (1,2,3).
The competition format requires a space delimited list of pairs. For example, '1 3 10 5' implies pixels 1,2,3,10,11,12,13,14 are to be included in the mask. The metric checks that the pairs are sorted, positive, and the decoded pixel values are not duplicated. The pixels are numbered from top to bottom, then left to right: 1 is pixel (1,1), 2 is pixel (2,1), etc.

 

  • 제출 형태뿐만 아니라, 모델 Training에 사용되는 String 포맷 RLE 데이터를 decoding 및 어레이를 reshape 하는 경우,
  • 이때도 역시 reshape 메서드 중 order='F' 옵션을 사용하여 1차원 어레이로 변화하는 등, fortran-like order를 사용하는 경우가 있다.

 

Option for Fortran-like order

 

결론적으로 이 메소드를 학습하면서 강조하고 싶었던 부분은, 용도에 맞게 어레이의 인덱스를 조정할 수 있어야 한다. 또한, encoding ↔️ decoding 간 일련의 과정을 이해하고 어레이의 인덱싱 Way 를 이해하는데 있다고 생각한다.

반응형