끵뀐꿩긘의 여러가지

Numpy 본문

Naver boostcamp -ai tech/week 01

Numpy

끵뀐꿩긘 2022. 9. 21. 13:30

Numpy: 수치해석용 파이썬 패키지

 

Numpy 특징:

 - 일반 List에 비해 빠르고, 메모리 효율적

 - 반복문 없이 데이터 배열에 대한 처리 지원

 - 선형대수와 관련된 다양한 기능 제공

 - C, C++ 등의 언어와 통합 가능

 - C의 데이터 타입을 가지고 있다

 

Numpy 패키지:

import numpy as np

 

Array Creation(np.array, ndarray 생성 함수): 

test_array = np.array([1, 4, 5, 8], float)

https://numpy.org/doc/1.23/reference/generated/numpy.array.html?highlight=array#numpy.array 

 

numpy.array — NumPy v1.23 Manual

If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

numpy.org

 

ndarray(클래스):

https://numpy.org/doc/1.23/reference/generated/numpy.ndarray.html?highlight=ndarray#numpy.ndarray 

 

numpy.ndarray — NumPy v1.23 Manual

An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floati

numpy.org

shape: dimension 구성 반환

dtype: 데이터 type 반환

ndim: number of dimensions

size: 데이터의 개수(전체 원소의 개수)

itemsize: 배열 각 멤버의 바이트 크기

astype: 데이터 타입 바꾸기

flag:배열의 특정 속성에 대해

x = numpy.array([1,2,3,4])
print(x.flags)

>>>
C_CONTIGUOUS : True    # Data가 C언어 기반의 데이터 세그먼트인지에 대한 확인
F_CONTIGUOUS : True    # Data가 Fortran언어 기반의 데이터 세그먼트인지에 대한 확인
OWNDATA : True    #객체가 메모리를 직접 소유하는지 아니면, 다름 객체를 참조하고 있는지 확인
WRITEABLE : True    #쓸수 있는지 즉, False의 경우, Read-Only
ALIGNED : True
UPDATEIFCOPY : False    #배열이 다른 배열을 복사한것인지에 대해 확인

 

데이터 타입(data type):

i - integer (정수)

b - boolean (참거짓)

u - unsigned integer (부호없는 정수)

f - float (소수)

c - complex (복소수)

m - timedelta (타임델타)

M - datetime (날짜시간)

O - object (객체)

S - string (문자열)

U - unicode string (유니코드 문자열)

V - void (다른 유형에 대한 고정된 메모리 덩어리) 

import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype) # int32 == I4

arr = np.array(['HTML', 'CSS', 'JS'])
print(arr.dtype) # <U4: 문자열 요소 중 가장 긴 길이를 의미한다
# <는 리틀 엔디안을 의미한다(바이트 저장 순서 관련)

구조화된 배열(structured Array):

구조화된 데이터 타입이란 서로 다른 데이터 타입으로 구성된 데이터 타입이다

name = ['kim', 'lee', 'park']
age = [20, 30, 35]
weight = [55.5, 70.0, 65.7]

# 구조화된 데이터 타입 생성
data = np.zeros(3, dtype={'names': ('name', 'age', 'weight'), 'formats': ('U10', 'i4', 'f8')})
print(data.dtype)
# [('name', '<U10'), ('age', '<i4'), ('weight', '<f8')]

# 구조화된 데이터 타입 접근
data['name'] = name
data['age'] = age
data['weight'] = weight

print(data)
# [('kim', 20, 55.5) ('lee', 30, 70. ) ('park', 35, 65.7)]

 

 

Array Shape:

Rank name
0 scalar
1 vector
2 matrix
3 3-tensor
n n-tensor

 

numpy.ndarray.shape:

array의 shape 크기

https://numpy.org/doc/1.23/reference/generated/numpy.ndarray.shape.html

 

numpy.ndarray.shape — NumPy v1.23 Manual

 

numpy.org

 

numpy.ndarray.flatten:

1차원 array로 변환

https://numpy.org/doc/1.23/reference/generated/numpy.ndarray.flatten.html

 

numpy.ndarray.flatten — NumPy v1.23 Manual

 

numpy.org

 

Indexing:

https://numpy.org/doc/1.23/reference/generated/numpy.ndarray.flatten.html

 

numpy.ndarray.flatten — NumPy v1.23 Manual

 

numpy.org

 

 

- any: 하나라도 조건에 만족하면 true, all :모두가 조건에 만족하면 true

a = np.arange(10)
np.any(a>5)
>>> True

-고급 인덱싱

import numpy as np

arr = np.array([[1,2,3,4],
                [5,6,7,8],
                [9,10,11,12],
                [13,14,15,16]])


rows = np.array([[0,0],
                [3,3]], dtype = np.intp)
columns = np.array([[0,2],
                   [0,2]],dtype = np.intp)

print(arr[rows,columns]) #[[ 1  3]
                         #[13 15]]

 

- boolean/fancy 인덱싱

특정 조건에 따른 값을 배열 형태로 추출하여 boolean/fancy 인덱싱을 통해 그 값들만 추출

condition = test_array < 3 # boolean 배열 반환
test_array[condition] # 조건에 맞는 값들만 반환

condition = np.where(test_array < 3)# 인덱스 배열 반환
test_array[condition]# 조건에 맞는 값들만 반환

 - numpy.nonzero(): 0이 아닌 요소의 인덱스를 반환한다

>>> a=np.array([[1, 0, 7], [8, 1, 0], [1, 0, 0]])
>>> a
array([[1, 0, 7],
       [8, 1, 0],
       [1, 0, 0]])
>>> np.nonzero(a)
(array([0, 0, 1, 1, 2]), array([0, 2, 0, 1, 0])) # 0이 아닌 값들의 index 반환

>>> np.transpose(np.nonzero(a)) # 좀더 편하게 볼 수 있음
array([[0, 0],
       [0, 2],
       [1, 0],
       [1, 1],
       [2, 0]])
       
>>>a[np.nonzero(a)] # 0이 아닌값 출력가능

newaxis:

numpy array의 차원을 늘려준다

arr = np.arange(4) # shape: (4,)

row_vec = arr[np.newaxis, :] # shape: (1,4)
row_vec = arr[None, :] # shape: (1,4)

column_vec = arr[: , np.newaxis] # shape: (4,1)
column_vec = arr[: , None] # shape: (4,1)

https://numpy.org/doc/stable/reference/constants.html?highlight=newaxis#numpy.newaxis 

 

Constants — NumPy v1.23 Manual

 

numpy.org

 

Createion Function:

- numpy.arange([start]stop[step]dtype=None*like=None):

https://numpy.org/doc/stable/reference/generated/numpy.arange.html?highlight=arange#numpy.arange 

 

- numpy.ones(shape, dtype=None, order='C', *, like=None):

https://numpy.org/doc/1.23/reference/generated/numpy.ones.html?highlight=ones#numpy.ones

 

- numpy.zeros(shapedtype=floatorder='C'*like=None):

https://numpy.org/doc/1.23/reference/generated/numpy.zeros.html?highlight=zeros#numpy.zeros 

 

- numpy.empty(shapedtype=floatorder='C'*like=None): 공간만 잡아줌

https://numpy.org/doc/1.23/reference/generated/numpy.empty.html?highlight=empty#numpy.empty 

 

- numpy.full(shapefill_valuedtype=Noneorder='C'*like=None): fill value로 채우기

https://numpy.org/doc/1.23/reference/generated/numpy.full.html?highlight=full#numpy.full 

 

- numpy.ones_like(adtype=Noneorder='K'subok=Trueshape=None): zeros_like도 있음, a랑 같은 크기

https://numpy.org/doc/1.23/reference/generated/numpy.ones_like.html?highlight=ones_like#numpy.ones_like 

 

- numpy.linspace(startstopnum=50endpoint=Trueretstep=Falsedtype=Noneaxis=0): num에 요소의 개수를 입력받아, 간격이 같은 array 반환

https://numpy.org/doc/1.23/reference/generated/numpy.linspace.html?highlight=numpy%20linspace#numpy.linspace 

 

- numpy.identity(ndtype=None*like=None): 단위행렬

https://numpy.org/doc/1.23/reference/generated/numpy.identity.html?highlight=identity#numpy.identity 

 

- numpy.eye(NM=Nonek=0dtype=<class 'float'>order='C'*like=None): 대각선이 1인 행렬

https://numpy.org/doc/1.23/reference/generated/numpy.eye.html?highlight=eye#numpy.eye 

 * k 값에 따라 시작 위치가 달라진다, k=1이면 대각선을 기준으로 1단계 위로 1이 배치된다

np.eye(3,k = 1)

 ** numpy.diag(vk=0): 대각행렬의 값 추출 -> k 값에 따라 시작 위치가 달라진다

 

- random.rand(d0d1...dn): 주어진 형태의 난수 생성

https://numpy.org/doc/1.23/reference/random/generated/numpy.random.rand.html?highlight=random%20rand#numpy.random.rand 

 

- random.randint(lowhigh=Nonesize=Nonedtype=int): low ~ high 범위에서 랜덤 정수 생성

https://numpy.org/doc/1.23/reference/random/generated/numpy.random.randint.html?highlight=numpy%20random%20randint 

 

- random.randn(d0d1...dn): 표준정규분포 N(1, 0)을 따르는 정규분포 난수 생성

https://numpy.org/doc/1.23/reference/random/generated/numpy.random.randn.html?highlight=numpy%20random%20randn#numpy.random.randn 

 * 정규분포 N(μσ^2)의 난수를 생성하기 위해서는 σ * np.random.randn(…) + μ로 사용가능

 

 - random.normal(loc=0.0scale=1.0size=None): 정규분포 N(loc, scale)을 따르는 난수 생성

https://numpy.org/doc/1.23/reference/random/generated/numpy.random.normal.html?highlight=random%20normal#numpy.random.normal 

 

 - random.random_sample(size=None): [0.0, 1.0) 범위에서 샘플링된 임의의 실수를 반환

https://numpy.org/doc/1.23/reference/random/generated/numpy.random.random_sample.html?highlight=random_sample#numpy.random.random_sample 

 

** random.seed(selfseed=None): 시드 설정

 

Operating Function:

add, multifly, sum, mean, std, exp, sqrt, sin, cos, tan, log, max, min, argmax, argmin(인덱스 찾기), unique(중복원소 제거), var(분산), median, cumsum(누적합계), np.where(인덱스 값 반환), isnan, isfinite,outer(외적), dot(행렬곱)

등등

 

*넘파이의 유니버셜 함수:

전체 배열에서 요소별로 작동하는 함수

파이썬은 동적 언어이기 때문에 효율적 컴파일이 불가능하다. 그러므로 벡터 연산을 수행할때 굉장히 느리다.

그런 단점을 보완하기 위해서 numpy에서는 유니버셜함수를 통해 Numpy 배열 앞에 반복된 연산을 빠르게 수행한다.

위의 Operating Function 중 일부가 파이썬의 연산을 대신한 유니버셜 함수이다.(+,*,% 등등이 알아서 유니버셜 함수로 변환된다)

- 기본연산(합, 곱, 나머지, 가우스, 헤비사이드, 인수의 역, 로그, exp,)부터 삼각함수 연산(sin , cos, degree to radian), 비트연산, 비교연산, 플로팅 연산(배열에서 요소단위로 적용되는 함수, isnan, isinf, ceil)을 포함한다

 

* numpy는 array간의 기본적인 (Element-wise)사칙연산을 지원하고, broadcasting을 통해 shape이 다른 배열간 연산을 지원한다

*broadcasting은 두배열의 shape을 비교한 차원이 동일하거나 하나가 1일때 호환가능

(ex. shape: (4,3) + (1,3) => 가능, shape: (4,3) + (2,3) => 불가능)

* numpy.dot(about=None): 매트릭스 연산 ,@

* numpy.ndarray.T : transpose

*다차원 배열의 전치:

A.transpose((2,1,0)) # == np.transpose(A, (2,1,0))
# 원래 A 배열의 axis 2(height)를 axis 0(row)로 , axis 1(column)를 axis 1(column)로,
# axis 0(row)를 axis 2(height)로 바꾼 것이다

# transpose안에 아무것도 안넣는다면:
# A.transpose()는 A.shape()를 reverse 한 것과 같아진다

참고: 다차원 배열의 전치

https://pybasall.tistory.com/124

 

[파이썬 numpy] 배열의 전치를 원하는 방향으로 (transpose 메소드)

[파이썬 numpy] 배열의 전치를 원하는 방향으로 (transpose 메소드) transpose 메소드는 T메소드보다 확장된 방법이다. T메소드는 배열의 shape을 역방향으로 바꾸는 것만 할 수 있지만 transpose 메소드는

pybasall.tistory.com

*ufunc.reduce(arrayaxis=0dtype=Noneout=Nonekeepdims=Falseinitial=<no value>where=True):

한 축을 따라 ufunc을 적용하여 a의 차원을 1개씩 축소한다

np.multiply.reduce([2,3,5])
>>> 30
# np.sum == np.add.reduce

https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduce.html?highlight=reduce#numpy.ufunc.reduce 

 

numpy.ufunc.reduce — NumPy v1.23 Manual

The value with which to start the reduction. If the ufunc has no identity or the dtype is object, this defaults to None - otherwise it defaults to ufunc.identity. If None is given, the first element of the reduction is used, and an error is thrown if the r

numpy.org

*ufunc.accumulate(array, axis=0, dtype=None, out=None):

모든 요소에 연산자를 적용한 결과를 축적한다

np.add.accumulate([2, 3, 5]) # 덧셈 누계
>>> array([ 2,  5, 10])
np.multiply.accumulate([2, 3, 5]) # 곱셈 누계
>>> array([ 2,  6, 30])

https://numpy.org/doc/stable/reference/generated/numpy.ufunc.accumulate.html?highlight=accumulate#numpy.ufunc.accumulate 

 

numpy.ufunc.accumulate — NumPy v1.23 Manual

A location into which the result is stored. If not provided or None, a freshly-allocated array is returned. For consistency with ufunc.__call__, if given as a keyword, this may be wrapped in a 1-element tuple. Changed in version 1.13.0: Tuples are allowed

numpy.org

*ufunc.outer(A, B, /, **kwargs):

모든 쌍(a,b)에 유니버셜 함수 연산인 ufunc을 적용한다

np.multiply.outer([1, 2, 3], [4, 5, 6])
>>> array([[ 4,  5,  6],
       [ 8, 10, 12],
       [12, 15, 18]])

https://numpy.org/doc/stable/reference/generated/numpy.ufunc.outer.html?highlight=outer#numpy.ufunc.outer 

 

numpy.ufunc.outer — NumPy v1.23 Manual

 

numpy.org

 

Axis(축):

axis개념을 나는 괄호로 이해했다. axis = 0은 가장 바깥쪽에 있는 괄호 axis의 값이 하나씩 커질수록 안쪽으로 한칸씩 들어간다

x = np.array([
    [ 1,  2,  3,  4],
    [ 5,  6,  7,  8],
    [ 9, 10, 11, 12],
])

x.sum(axis = 0)
# axis = 0이므로 가장 바깥괄호를 없애고 서로 더한다.
# 그러면 [1,2,3,4] + [5,6,7,8] + [9,10,11,12]가 되므로
# 원소 위치에 맞게 더해주면 [15,18,21,24]가 된다

x.sum(axis = 1)
# axis = 1이므로 바깥에서 두번재 괄호를 없애고 서로 더한다
# 그러면 [1+2+3+4,5+6+7+8,9+10+11+12]가 되므로
# 원소 위치에 맞게 더해주면 [10,26,42]가 된다

arr.shape에서 나오는 순서대로 axis의 번호가 매겨진다.

ex. 2차원 배열.shape = (2,3) => axis 0: column, axis 1: row

3차원 배열.shape = (2,2,3) => axis 0: height(채널의 개수), axis 1: column, axis 2: row

 

concatenate:

- numpy.concatenate((a1a2...)axis=0out=Nonedtype=Nonecasting="same_kind"):

axis = 0 수직으로 합치기, axis =1 수평으로 합치기

https://numpy.org/doc/1.23/reference/generated/numpy.concatenate.html?highlight=concatenate#numpy.concatenate 

 

- numpy.vstack(tup): 튜플로 주어진 array 수직으로 합치기

https://numpy.org/doc/1.23/reference/generated/numpy.vstack.html?highlight=vstack#numpy.vstack 

 

 

- numpy.hstack(tup): 튜플로 주어진 array 수평으로 합치기

https://numpy.org/doc/1.23/reference/generated/numpy.hstack.html?highlight=hstack#numpy.hstack 

 

** 주피터 퍼포먼스 측정:

매직 커맨드 적용 범위 의미
%time 라인 명령어 뒤에 한줄 코드가 수행되는데 걸리는 시간을 반환합니다.
%timeit 라인 time + iteration 으로 이해하시면 됩니다. 명령어 뒤에 한줄 코드를 몇번 반복 수행 후 평균 시간을 반환합니다.
%%time %를 두개 적으면, Cell 전체에 적용이 됩니다. 즉, Cell 코드를 모두 수행한 후 시간을 측정하여 반환합니다.
%%timeit %를 두개 적으면, Cell 전체에 적용이 됩니다. 즉, Cell 코드를 모두 반복 수행한 후 평균 시간을 측정하여 반환합니다.
%timeit x = cal() # cal의 퍼포먼스 측정
y = cal()

 

load & save:

save & load: npy 파일로 저장 로드

savetxt & loadtxt: 텍스트 파일로 저장 로드

savez: 여러개의 배열을 압축되지 않은 npz 파일로 저장

savez_compressed: 여러개의 배열을 압축된 npz 파일로 저장

import numpy as np

# 배열을 저장하기
x = np.array([0, 1, 2, 3, 4])
np.save('D:/admin/Documents/x_save', x) # x_save.npy[ .npy 형식으로 저장된 파일 ]

# 배열로 불러오기
x_save_load = np.load('D:/admin/Documents/x_save.npy')
x_save_load Out[5]: array([0, 1, 2, 3, 4])

 

뷰와 복사:

numpy 배열을 슬라이싱하면 원본의 참조인 view가 생성된다.

즉, 원본이 바뀌면 슬라이싱한 view도 바뀌게 된다.

데이터 영역에 또 다른 데이터 타입을 할당하면 이 또한 view로 원본을 참조한다

# 슬라이싱 view
arr = np.arange(3) # [0,1,2]
v = arr[1:2] # [1]
arr[1] = 7
v # [7]

# 데이터 타입 체인지
arr = np.zeros(2, dtype=np.uint16) # arr([0,0], dtype=np.uint16)
arr.view(np.uint8) # arr([0,0,0,0], dtype = uint8) # 같은 공간을 다른 데이터 타입을 보았기 때문
arr.astype(np.uint8) # arr([0,0], dtype=np.uint8)  # 데이터 타입을 변화하였음

# arr.strides # 특정 축에서 한 단계 이동하기 위해서 메모리에서 이동할 바이트 수

 

numpy 배열을 불리언으로 인덱싱하면 arr 중 해당하는 부분의 복사를 반환한다

복사 배열의 요소를 변경하더라도, 원본 배열의 요소에는 변화가 없고 역도 그렇다

# 복사
arr = np.arange(3) # [0,1,2]
v = arr[arr>1] # 불린 인덱싱으로 복사배열을 반환한다

arr.copy() # 복사 배열 반환
np.array(arr) # 복사 배열 반환

np.asarrasy(arr) # 참조 배열 반환, 전체 뷰 생성

# base, 복사배열x와 참조배열 y가 있다고 할때
x.base # None
y.base # 원본 배열 반환

넘파이는 복사보다 뷰를 사용함으로써 메모리에 주는 부담을 줄여 처리 속도를 높인다

 

 

flatiter:

배열을 반복하는 플랫 반복자 객체

 

>>> x = np.arange(6).reshape(2, 3)
>>> fl = x.flat
>>> type(fl)
<class 'numpy.flatiter'>
>>> for item in fl:
...     print(item)
...
0
1
2
3
4
5

#f1.coords # 현재 좌표를 N차원 튜플로 표기한다 ex. (0,1)

# 배열을 for문에 그냥 넣으면 배열의 하위 요소를 뱉는다
# ex. (0,1,2)

flat을 적용하면 고차원 배열이 반복 처리할 수 있는 1차원 배열이 된다.

 

np.linalg:

선형 대수학 모듈

dot: 행렬곱

outer: 외적

linalg.solve: 선형 방정식 풀이

linalg.inv:  행렬의 역수 

linalg.pinv: 유사 역행렬

'Naver boostcamp -ai tech > week 01' 카테고리의 다른 글

선형대수학  (1) 2022.09.22
pandas  (0) 2022.09.21
CSV, XML, JSON data 파이썬으로 핸들링하기  (1) 2022.09.20
정규표현식  (0) 2022.09.20
부족한 python 채우기  (1) 2022.09.20
Comments