numpy API : Rounding과 정렬 함수

김상윤·2023년 3월 3일
0

Rounding

소수점 아래 숫자가 많은 경우 출력을 할때 보기 좋지 않은 경우가 있다. 이런 경우 rounding을 통해 소수점 아래 몇자리까지만 표기/ 출력하는 기능을 수행할 수 있다. 연산에 직접적으로 사용하기에는 위험 부담이 존재한다. 딥러닝에서 소수점 아래 숫자들이 굉장히 중요할 가능성도 있기 때문에 데이터를 출력할 때만 사용하기를 권한다.

Round

numpy.around(a, decimals=0, out=None)
numpy.round_(a, decimals=0, out=None)
np. 일때는 around 혹은 round_를 쓴다. 이것은 Python 자체적으로 제공하는 api와의 namespace가 겹치지 않도록 하기 위함이다.
ndarray.round(decimals=0, out=None)

import numpy as np

x = np.random.uniform(-5, 5, (5,))

np_around = np.around(x, decimals = 2)
np_round = np.round_(x, decimals = 2)
x_round = x.round(decimals = 2)

decimals는 최종적으로 표기될 소수점의 자리수를 나타낸다.

Ceiling, Flooring

numpy.ceil(x,/,out = None,...)
numpy.floor(x,/,out = None,...)
Ceiling과 Flooring은 정수를 만들어 주는 API이다.

import numpy as np

x = np.random.uniform(-5,5,(5,))

ceil = np.ceil(x)
floor = np.floor(x)

x : [-4.0323, 1.23342, 3.643422, -3.42342, 4.922342]
ceil : [-4., 2., 4., -3., 5.]
Floor : [-5., 1., 3., -4., 4.]

Ceil은 더 큰 정수로 만들어주고 Floor는 더 작은 정수를 만들어준다. 음수에서 조심할 것.

Truncation

numpy.truc(x, /, out=None,...)
Truncation은 소수점을 통째로 날려버리는 API이다.

import numpy as np
x = np.random.uniform(-5,5,(5,))

trunc = np.trunc(x)
x : -4.43422, 1.32342, 3.45213 -3.42342, 4.922342]
trunc : [-4., 1., 3., -3., 4.]

Truncation을 where로 구현하기

import numpy as np

x = np.random.uniform(-5,5,(5,))

trunc_where = np.where(x >= 0, np.floor(x), np.ceil(x))

"양수 일때는 flooring, 음수일 때는 ceiling을 해준다"라고 생각할 수 있다.

활용

import numpy as np
x = np.random.uniform(-5,5,(5,))
trunc = 0.1 * np.trunc(10*x) #소수점 첫번째까지 표현
trunc = 0.01 * np.trunc(100*x) #소수점 두번째까지 표현

int_part = np.trunc(x)
decimal_part = np.trunc(x)

Sorting

Sort & Argsort

numpy.sort(a, axis=-1) value에 대해서 sorting하고 value를 반환
numpy.argsort(a, axis=-1) value에 대해서 sorting하고 index를 반환

Sorting Vectors

import numpy as np

pred = np.random.uniform(0,100, (5,))
pred /= pred.sum()

top3_pred = np.sort(pred)[::-1][:3]
top3_indices = np.argsort(pred)[::-1][:3]

pred.round(3) 		[0.113, 0.183, 0.228, 0.378, 0.098]
top3_pred.round(3) 	[0.378, 0.228, 0.183]
top3_indices 		[3, 2, 1]

sort는 작은 순서대로 정렬을 하기 때문에 reverse 한번 해주고 그 중에서 앞에 3개를 slicing하면 top3 prediction을 구할 수 있다.

import numpy as np

x = np.random.randint(0,100,(4,5))

sort = np.sort(x, axis=0)
argsort = np.argsort(x, axis=0)

x  [[99 59 19 4 75]
	[50 37 78 47 76]
    [42 49 28 84 96]
    [6 78 56 84 96]]
    
sort [[6 37 19 4 45]
	  [42 49 28 47 75]
      [50 59 56 56 76]
      [99 78 78 84 96]]
      
argsort [[3 1 0 0 3]
		 [2 2 2 1 0]
         [1 0 3 3 1]
         [0 3 1 2 2]]

column을 오름차순으로 정렬하고 낮은 순서대로 index를 반환하는 코드이다
내림차순으로 정렬하기 위해서는 다음과 같이 하면 된다.
sort = np.sort(x, axis=0)[::-1,:] -> 중요!!

Sorting Matrix in column

import numpy as np
score = np.random.randint(0,100, (5,3))

sort = np.sort(score, axis=0)[::-1,:] -> top2_score
argsort = np.argsort(scores, axis=0)[::-1,:] -> top2_student

Sorting Matrix in row

import numpy as np

x = np.random.randint(0, 100, (4,5))

sort_ascending = np.sort(x, axis = 1)
argsort_ascending = np.argsort(x, axis =1)

sort_descending = np.sort(x, axis = 1)[:,::-1]
argsort_descending = np.argsort(x, axis =1)[:,::-1]

row가 예를 들어 하나의 이미지에 대한 예측 결과를 나타내는 경우가 있다. 그럴 경우 top5 예측이 무엇인지 정렬하는 것이 중요하다. 그럴 경우 axis = 1 에 대하여 정렬을 진행한다.

profile
AI 대학원 지망생

0개의 댓글