본문 바로가기

CS/Python

Numerical Python - Numpy(3)

@Numpy performance

 

-일반적 속도

 numpy > list comprehension > for loop

 

-100,000,000번의 loop가 돌 때 약 4배 이상의 성능 차이를 보임

-Numpy는 C로 구현되어 있어, 성능을 확보하는 대신 파이썬의 가장 큰 특징인 Dynamic typing을 포기함

-대용량 계산에서는 가장 흔히 사용됨

-but, concatenate 처럼 계산이 아닌, 할당에서는 연산 속도의 이점이 없으므로 list comprehension을 사용한 후 numpy로 바꿔주는 게 좋음

 

 

  • Using for loop

def sclar_vector_product(scalar, vector):
    result = []
    for value in vector:
        result.append(scalar * value)
    return result 

iternation_max = 100000000

vector = list(range(iternation_max))
scalar = 2

%timeit sclar_vector_product(scalar, vector) 

 

  • Using list comprehension

%timeit [scalar * value for value in range(iternation_max)]

 

  • Using numpy

%timeit np.arange(iternation_max) * scalar

 

 

 

 

@All & Any

-Array의 데이터 전부(and) 또는 일부(or)가 조건에 만족하는지 여부 반환

-Numpy에서 값 비교할 때 쓰임. 일종의 broadcasting이 일어났다고 보면 됨

 

import numpy as np

test = np.arange(10)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(test > 5)

output)

[False, False, False, False, False, False,  True,  True,  True,  True]

-비교한 결과 값을 list 형태로 반환

 

 

import numpy as np

test = np.arange(10)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(np.any(test > 5), np.any(test < 0))

output)

True False

 

 

import numpy as np

test = np.arange(10)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(np.all(test > 5), np.all(test < 10))

output)

False True

 

 

 

 

@np.where

-조건에 만족하는 index값 출력

-index값 반환시 많이 사용

 

import numpy as np

a = np.array([1, 3, 0], float)
# [ 1.,  3.,  0.]

print(np.where(a > 0, 3, 2))

a가 0보다 크면 3반환, 크지 않으면 2반환

 

output)

[3 3 2]

 

 

 

 

@argmax & argmin

-array index 중 각각 최대값, 최소값의 index num 반환

 

import numpy as np

a = np.array([1, 2, 4, 5, 8, 78, 23, 3])
print(np.argmax(a), np.argmin(a))

output)

5 0

 

 

-axis 기반의 반환

 

import numpy as np

a = np.array([[1, 2, 4, 7], [9, 88, 6, 45], [9, 76, 3, 4]])
print(np.argmax(a, axis=1), np.argmin(a, axis=0))

output)

[3 1 1] [0 0 2 2]

 

 

 

*Numpy에 for loop 쓰는 버릇을 고쳐야 함

 -> 여러 지원되는 함수들 활용하기

 

 

 

 

@boolean index

-Numpy array는 특정 조건에 따른 값을 배열 형태로 추출 가능

-Comparison operation 함수들도 모두 사용 가능

 

import numpy as np

test = np.array([1, 4, 0, 2, 3, 8, 9, 7], float)
print(test > 3)
# [False  True False False False  True  True  True]

print(test[test > 3])

조건이 true인 index의 element만 추출

 

 

import numpy as np

A = np.array([
    [12, 13, 14, 12, 16, 14, 11, 10, 9],
    [11, 14, 12, 15, 15, 16, 10, 12, 11],
    [10, 12, 12, 15, 14, 16, 10, 12, 12],
    [9, 11, 16, 15, 14, 16, 15, 12, 10],
    [12, 11, 16, 14, 10, 12, 16, 12, 13],
    [10, 15, 16, 14, 14, 14, 16, 15, 12],
    [13, 17, 14, 10, 14, 11, 14, 15, 10],
    [10, 16, 12, 14, 11, 12, 14, 18, 11],
    [10, 19, 12, 14, 11, 12, 14, 18, 10],
    [14, 22, 17, 19, 16, 17, 18, 17, 13],
    [10, 16, 12, 14, 11, 12, 14, 18, 11],
    [10, 16, 12, 14, 11, 12, 14, 18, 11],
    [10, 19, 12, 14, 11, 12, 14, 18, 10],
    [14, 22, 12, 14, 11, 12, 14, 17, 13],
    [10, 16, 12, 14, 11, 12, 14, 18, 11]])
B = A < 15
print(B.astype(np.int))

output)

[[1, 1, 1, 1, 0, 1, 1, 1, 1],
 [1, 1, 1, 0, 0, 0, 1, 1, 1],
 [1, 1, 1, 0, 1, 0, 1, 1, 1],
 [1, 1, 0, 0, 1, 0, 0, 1, 1],
 [1, 1, 0, 1, 1, 1, 0, 1, 1],
 [1, 0, 0, 1, 1, 1, 0, 0, 1],
 [1, 0, 1, 1, 1, 1, 1, 0, 1],
 [1, 0, 1, 1, 1, 1, 1, 0, 1],
 [1, 0, 1, 1, 1, 1, 1, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 1, 1, 1, 1, 1, 0, 1],
 [1, 0, 1, 1, 1, 1, 1, 0, 1],
 [1, 0, 1, 1, 1, 1, 1, 0, 1],
 [1, 0, 1, 1, 1, 1, 1, 0, 1],
 [1, 0, 1, 1, 1, 1, 1, 0, 1]]

 

 

 

 

@fancy index

-Numpy array를 index value로 사용해 값 추출하는 방법

 

import numpy as np

a = np.array([2, 4, 6, 8], float)
b = np.array([0, 0, 1, 3, 2, 1], int)  # Must be declared as int
print(a[b])

output)

[2. 2. 4. 8. 6. 4.]

a[b]가 아니라 a.take(b)해도 같은 값 출력됨

모양이 명확하기 때문에 take 함수를 사용하는 것을 더 추천!

 

 

-Matrix 형태의 데이터도 가능

 

import numpy as np

a = np.array([[1, 4], [9, 16]], float)
b = np.array([0, 0, 1, 1, 0], int)
c = np.array([0, 1, 1, 1, 1], int)
print(a[b, c])  # Convert b to row index and c to column index to display

output)

[ 1.  4. 16. 16.  4.]

 

 

 

'CS > Python' 카테고리의 다른 글

Pandas  (0) 2021.02.27
Numpy data i/o  (0) 2021.02.20
Numerical Python - Numpy(2)  (0) 2021.02.20
Numerical Python - Numpy(1)  (0) 2021.02.18
PCA: How to use in Python  (0) 2021.02.08

Tiny Star