kwan's note

Data Handling - Assignment(Numpy Lab) 본문

ML and AI/Python for ML

Data Handling - Assignment(Numpy Lab)

kwan's note 2021. 1. 17. 14:03
반응형

출처: 부스트코스-머신러닝을 위한 파이썬

수강일시:2021.01.17

www.boostcourse.org/ai222/lecture/24072

 

머신러닝을 위한 파이썬

부스트코스 무료 강의

www.boostcourse.org

 

넘파이 연습을 위한 예제

 

github.com/TEAMLAB-Lecture/AI-python-connect/blob/master/lab_assignments/lab_2/README.md#zero_or_one_or_empty_ndarray

 

TEAMLAB-Lecture/AI-python-connect

Contribute to TEAMLAB-Lecture/AI-python-connect development by creating an account on GitHub.

github.com

 

본 Lab은 Numpy의 실행 방법을 이해하기 위해 8개의 함수를 작성해야 합니다. 각 함수별 구체적인 작성 방법은 아래와 같습니다. 단 본 랩은 for loop을 사용할 경우, 틀린 걸로 처리합니다. 반드시 numpy 로만 처리하시기 바랍니다.

 

n_size_ndarray_creation

  • Template

def n_size_ndarray_creation(n, dtype=np.int): X = None return X

  • 함수목적
    • n의 제곱수로 2 dimentional array를 생성하는 ndarray.
  • Args
    • n: 생성하고자 하는 ndarray의 row와 column의 개수
    • dtype: 생성하려는 ndarray의 data type (np.int)
  • Returns
    • row와 column의 길이가 n인 two dimentional ndarray로 X[0,0]은 0으로 순차적으로 X[n-1,n-1]은 n^2-1이 할당됨

zero_or_one_or_empty_ndarray

  • Template

def zero_or_one_or_empty_ndarray(shape, type=0, dtype=np.int): X = None return X

  • 함수목적
    • shape이 지정된 크기의 ndarray를 생성, 이때 행렬의 element는 type에 따라 0, 1 또는 empty로 생성됨.
  • Args
    • shape: 생성할려는 ndarray의 shape
    • type: 생성되는 element들의 값을 지정함0은 0, 1은 1, 99는 empty 타입으로 생성됨
    • dtype: 생성하려는 ndarray의 data type (np.int)
  • Returns
    • shape의 크기로 생성된 ndarray로 type에 따라 element의 내용이 변경됨

def change_shape_of_ndarray(X, n_row): return X

  • 함수목적
    • 입력된 ndarray X를 n_row의 값을 row의 개수로 지정한 matrix를 반환함.
    • 이때 입력하는 X의 size는 2의 거듭제곱수로 전제함.
    • 만약 n_row과 1일 때는 matrix가 아닌 vector로 반환함.
  • Args
    • X: 입력하는 ndarray
    • n_row: 생성할려는 matrix의 row의 개수
  • Returns
    • row의 개수가 n_row인 Matrix 또는 Vector
    • n_row가 1이면 Vector 값으로 반환함

def concat_ndarray(X_1, X_2, axis): pass

  • 함수목적
    • 입력된 ndarray X_1과 X_2를 axis로 입력된 축을 기준으로 통합하여 반환하는 함수
    • X_1과 X_2는 matrix 또는 vector 임, 그러므로 vector 일 경우도 처리할 수 가 있어야 함
    • axis를 기준으로 통합할 때, 통합이 불가능하면 False가 반환됨.
    • 단 X_1과 X_2 Matrix, Vector 형태로 들어왔다면, Vector를 row가 1개인 Matrix로 변환하여 통합이 가능한지 확인할 것
  • Args
    • X_1: 입력하는 ndarray
    • X_2: 입력하는 ndarray
    • axis: 통합의 기준이 되는 축 0 또는 1임
  • Returns
    • X_1과 X_2과 통합된 matrix 타입의 ndarray

def normalize_ndarray(X, axis=99, dtype=np.float32): pass

  • 함수목적
    • 입력된 Matrix 또는 Vector를 ndarray X의 정규화된 값으로 변환하여 반환함
    • 이때 정규화 변환 공식 Z = (X - X의평균) / X의 표준편차로 구성됨.
    • X의 평균과 표준편차는 axis를 기준으로 axis 별로 산출됨.
    • Matrix의 경우 axis가 0 또는 1일 경우, row 또는 column별로 Z value를 산출함.
    • axis가 99일 경우 전체 값에 대한 normalize 값을 구함.
  • Args
    • X: 입력하는 ndarray,
    • axis: normalize를 구하는 기준이 되는 축으로 0, 1 또는 99임, 단 99는 axis 구분 없이 전체값으로 평균과 표준편차를 구함
    • dtype: data type으로 np.float32로 구정
  • Returns
    • 정규화된 ndarray

 

제출

import numpy as np

def n_size_ndarray_creation(n, dtype=np.int):
    return np.arange(n**2,dtype=dtype).reshape(n,n)

print(n_size_ndarray_creation(3))


def zero_or_one_or_empty_ndarray(shape, type=0, dtype=np.int):
    if type == 0 :
        return np.zeros(shape=shape, dtype = dtype)
    elif type ==1:
        return np.ones(shape=shape, dtype = dtype)
    elif type ==99:
        return np.empty(shape=shape, dtype = dtype)

print(zero_or_one_or_empty_ndarray(shape=(2,2), type=1))

def change_shape_of_ndarray(X, n_row):
    return X.flatten() if n_row ==1 else X.reshape(n_row,-1)

print(change_shape_of_ndarray(n_size_ndarray_creation(3), 1))


def concat_ndarray(X_1, X_2, axis):
    try:
        if X_1.ndim ==1:
            X_1 = X_1.reshape(1,-1)
        if X_2.ndim == 1:
            X_2 = X_2.reshape(1, -1)
        return np.concatenate((X_1,X_2), axis =axis)
    except :
        return False

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
print(concat_ndarray(a, b, 0))

c= np.array([5,6,7,8])
print(concat_ndarray(b, c, 1))

def normalize_ndarray(X, axis=99, dtype=np.float32):
    n_row ,n_col = X.shape
    if axis ==99:
        return (X-np.mean(X))/np.std(X)
    elif axis ==0:
        return (X - np.mean(X,0).reshape(1,-1)) / np.std(X,0).reshape(1,-1)
    elif axis ==1:
        return (X - np.mean(X, 1).reshape(n_row, -1)) / np.std(X, 1).reshape(n_row, -1)
    else:
        return False
반응형