A. Development/for Machine Learning

Numpy 문법, API, 환경설정 / HDF5를 위한 H5PY API

IMCOMKING 2015. 12. 1. 14:26

Numpy 기본 레퍼런스
http://docs.scipy.org/doc/numpy/reference/

 

 

 

# Numpy object 인지 type check하기

type(a).__module__ == np.__name__ True

https://stackoverflow.com/questions/12569452/how-to-identify-numpy-types-in-python



# 잘 모르는 유용한 method

- np.triu: upper triangle matrix를 만든다.( == lower triangle을 0으로 만든다)

- np.tril: lower triangle matrix를 만든다.( == lower triangle을 0으로 만든다)
- np.cumprod: 주어진 axis로 cumulative product를 한다.
- np.dot: dot product를 한다.
- np.flipud: matrix의 위와 아래를 대칭으로 뒤집는다.

- np.fliplr: matrix의 왼쪽과 오른쪽을 대칭으로 뒤집는다.

 

- np.roll : element를 1개씩 뒤로 보낸다
https://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html

 

- np.isin : element wise로 특정 element가 다른 matrix안에 들어있는지 확인한다.
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isin.html

 

- np.tile : 내가원하는 방향으로 matrix를 확장복사한다.(repmat)
https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html

 

- np,array_split

 

- np.digitize: Quantization fucntion.
right = False -->  In edge case, the right point doesn't included to the left side.
https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.digitize.html

- np.percentile: Piece-wise Linear interpolation
https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.percentile.html

d = np.array([-5,-5,-5,-5, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3])
print(np.percentile(a=d, q=[0, 22, 33, 66, 77, 100], interpolation='linear'))
print(np.percentile(a=d, q=[0, 22, 33, 66, 77, 100], interpolation='midpoint'))

 

 

매틀랩 유저를 위한 Numpy 메뉴얼

http://mathesaurus.sourceforge.net/matlab-numpy.html

 

매틀랩에서의 Cell은 Numpy 에서 list 에 해당한다.
http://stackoverflow.com/questions/1761419/matlab-like-structure-cell-array-in-numpy

매틀랩에서는 인덱스가 1부터 시작하고, Numpy에서는 0부터 시작한다.

매틀랩에서는 [1:10]을 하면 10을 포함한 숫자가 인덱싱 되지만, Numpy에서는 9까지의 숫자가 인덱싱 된다.(대신 시작 인덱스가 0부터라서 Numpy방식이 더 편리함)

 

 

Numpy / MATLAB

matlab
load('파일명')

Numpy
np.loadtxt('파일명')

 

 

Numpy 고급 테크닉

 

 

 

 

Numpy 문법

 

# Numpy array에 string 저장하기
- np.array( (가로,세로), dytpe = 'a20')
--> a20: 최대 20글자의 string array

https://stackoverflow.com/questions/6999617/how-to-assign-a-string-value-to-an-array-in-numpy

https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html

 

 

for p, w in zip(model.layers[1].params, weights_list):

zip 은 그냥 2개를 하나로 묶어서 집합처럼 만들어 주는 것임.

http://pyengine.blogspot.kr/2014/03/python-zip.html

 

 

#trainX = imageData['trainX'][:]

 

# 넘파이 기본이 float 64임 따라서 float 32으로 바꿔야함/ asarray로

# resizing 하면 반드시 255로 다시 나눠줘야함. 0~1사이로 맞춰줘야해서

 

numpy에서 1개짜리 dimension 삭제는 squeeze로 함

numpy dim shuffle은 transpose로 함.

np.transpose(x, (1, 0, 2))

 

numpy reshape

print(X_train.shape, 'train samples') #(60000, 28, 28)

X_train = X_train.reshape(X_train.shape[0], -1, 1)

print(X_train.shape, 'train samples') #(60000, 784, 1)

 

- numpy ndarray에서 1차원 늘리기

tensor = tensor[: , : , np.newaxis]

- numpy ndarray에서 1차원만 고르기

matrix = tensor[ : , : , 0:1] # 그냥 0 하면 1차원이 아이에 날아가버린다

 

Numpy API

 

unique 함수 : elements 중에서 중복되지 않는 집합만 추출한다.
u, indices = np.unique(a, return_index=True)

 

#trainX = np.transpose(trainX, (0, 3, 1, 2))

 

- np.vstack : row dim에대해 array를 하나씩 쌓아주는 함수. 유사하게 hstack 함수도 존재
https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html

* 그런데 이 함수는 하위호환성을 위해 존재하는 것이고, np.concatenate 혹은 np.stack을 사용할 것을 권장한다.

 

HDF5를 위한 H5py API

 

 

 

#print vgg16_weights.keys()

#print vgg16_weights.values()

#print vgg16_weights.items()

#print vgg16_weights.attrs.items()

 

 

plt.imshow(drawX, cmap=plt.get_cmap('gray'), interpolation='nearest') # do not use anti-aliasing

X = kth_shuffled["X"][()] # it must need [()] to fully upload in memory

hdf5는 헤더만가져옴.