numpy로 broadcasting, vector,matrix 연산 구현
numpy 라이브러리를 사용한 broad casting 및 vector, dotproduct, multiplication matrix 를 python 코드로 구현한 것:
ReLU 함수 구현 :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def naive_relu(x): assert len(x.shape) == 2 x = x.copy() for i in range(x.shape[0]): for j in range(x.shape[1]): x[i,j] = max(x[i,j], 0) return x a = np.array([[1,2,-2,4,5], [1,-1,3,-4,5]]) a = naive_relu(a) print(a) |

행렬덧셈 :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def naive_add(x,y): assert len(x.shape) == 2 assert x.shape == y.shape x = x.copy() for i in range(x.shape[0]): for j in range(x.shape[1]): x[i,j] += y[i,j] return x b = np.array([[1,1,1,1,1], [1,1,1,1,1]]) result = naive_add(a,b) print(result) |

브로드 캐스팅 :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def naive_add_matrix_and_vector(x,y): assert len(x.shape) == 2 assert len(y.shape) == 1 assert x.shape[1] == y.shape[0] x = x.copy() y = y.reshape(1,-1) for i in range(x.shape[0]): for j in range(x.shape[1]): x[i,j] += y[0,j] return x x = np.array([[1,1,1], [1,1,1]]) y = np.array([1,1,1]) result = naive_add_matrix_and_vector(x,y) print(result) |
![]()
점곱연산 :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def naive_vector_dot(x,y): assert len(x.shape) == 1 assert len(y.shape) == 1 assert x.shape[0] == y.shape[0] z = 0. for i in range(x.shape[0]): z += x[i] * y[i] return z x = np.array([1,1,1]) y = np.array([1,1,1]) result = naive_vector_dot(x,y) print(result) |
![]()
행렬곱 연산 :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
def general_multiple_matrix(x,y): assert len(x.shape) == 2 assert len(y.shape) == 2 assert x.shape[1] == y.shape[0] z = np.zeros((x.shape[0],y.shape[1])) for i in range(x.shape[0]): for j in range(y.shape[1]): row_x = x[i, :] column_y = y[:,j] z[i,j] = naive_vector_dot(row_x, column_y) return z x = np.array([[1,2,3], [1,2,3]]) y = np.array([[1,2], [1,2], [1,2]]) print(general_multiple_matrix(x,y)) |
![]()