-
벡터와 매트릭스 ( Vectors and Matrices )-N131파이썬(판다스, AI,데이터 분석) 2021. 5. 22. 07:45
넘파이 기본
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters""" 넘파이는 벡터 및 행렬 연산에 있어서 많은 편의성을 제공한다. 판다스와 맷플롯립 등의 기반이 되는 라이브러리다. 기본적으로 array라는 단위로 데이터를 관리한다. """ # 넘파이 사용하기 import numpy as np # Array data = [1,2,3,4,5] data_arr = np.array(data) #array = np.array(파이썬 리스트) #out : array([1,2,3,4,5]) data_arr.shape #out : (5,) data_arr.dtype #out : dtype('int64') arr = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]) """ out : array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]]) """ arr.shape # out : (4,3) 1. numpy shape
numpy에서는 해당 array 의 크기를 알 수 있다
array를 저장한 변수명.shape --> ([]개수,[]안에 있는 요소 개수)
위의 예처럼 (5,)는 1차원 데이터이며 총 5라는 크기를 갖고 있다.
(4,3)은 2차원의 데이터라고 브루며 4*3의 크기를 갖고 있는 array이다.
2. numpy 자료형 (array를 저장한 변수명.dtype)
부호가 있는 정수 int(8,16,32,64)
부호가 없는 정수 unit(8,16,32,54)
실수 float(16,32,64,128)
복소수 complex(64,128,256)
불리언 bool
문자열 strint_
파이썬 오브젝트 object
유니코드 unicode_
3. np.zeros() , np.ones(), np.arange() 함수
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport numpy as np np.zeros(10) #out : array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) np.zeros((3,5)) """ out : array([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) """ np.ones(9) # out : array([1., 1., 1., 1., 1., 1., 1., 1., 1.]) np.ones((2,10)) """ out : array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]]) """ np.arange(10) # out : array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) np.arange(3,10) # out : array([3, 4, 5, 6, 7, 8, 9]) 4. Array 연산
numpy에서 연산을 할 떄는 크기가 서로 동일한 array 끼리 연산이 진행된다.
<script src="https://gist.github.com/Kim-yk/7ecb71b17249d1ce277bdc931f75ac63.js"></script>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersarr1 = np.array([[1,2,3],[4,5,6]]) arr2 = np.array([[10,11,12],[13,14,15]]) 4-1 array 덧셈
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersarr1 + arr2 """ array([[11, 13, 15], [17, 19, 21]]) """ 4-2 array 뺄셈
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersarr1 - arr2 """ array([[-9, -9, -9], [-9, -9, -9]]) """ 4-3 array 곱셈
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersarr1 * arr2 """ array([[10, 22, 36], [52, 70, 90]]) """ 4-4 array 나눗셈
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersarr1 / arr2 """ array([[0.1 , 0.18181818, 0.25 ], [0.30769231, 0.35714286, 0.4 ]]) """ 4-5 numpy의 브로드 캐스트 기능
위에서는 array가 같은 크기를 가져야 서로 연산이 가능하지만, numpy에서는 브로드캐스트라는 기능을 제공한다.
브로드캐스트란, 서로 크기가 다른 array끼리 연산이 가능하게 하는 기능이다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersarr1 = ([[1,2,3],[4,5,6]]) arr1.shape # out : (2, 3) arr3 = np.array([10,11,12]) arr3.shape # out : (3,) arr1 + arr3 """ out : array([[11, 13, 15], [14, 16, 18]]) """ arr1 * arr3 """ out : array([[10, 22, 36], [40, 55, 72]]) """ arr1*10 """ out : array([[10, 20, 30], [40, 50, 60]]) """ arr1 ** 2 """ out : array([[ 1, 4, 9], [16, 25, 36]]) """ 5 array 인덱싱 하기
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersarr1 = np.arange(10) arr1 # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) #n번쨰 요소 arr1[2] # out : 2 arr1[5] # out : 5 arr[2:5] #out : array([2,3,4]) arr[1:6] #out : array([1,2,3,4,5]) arr1[:] #out : array([0,1,2,3,4,5,6,7,8,9]) arr2 = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) """ 2차원 array에서 인덱싱을 하기 위해선 2개의 인자를 입력해야 한다. array가 담긴 변수명.[행,[]안의 요소 인덱스 넘버] """ arr2[0,0] # out : 1 arr[2,:] # 2행의 모든 요소 # out : array([9,10,11,12]) arr[2,3] #2행의 3번째 요소 # out : 12 arr[:,3] #모든 행의 3번째 요소 array([4, 8, 12]) 6 array 마스크 (boolean 인덱싱)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters""" array 마스크 boolean 인덱싱이라고도 불리며, 이 기능을 통해 array를 통해 우리가 원하는 행 또는 열의 값만 뽑아 낼 수 있다. """ names = np.array(['a','b','c','e','f','g','h','i']) """ out : array(['a','b','c','e','f','g','h','i'], dtype='<U1') names.shape out : (8,) """ data = np.random.randn(8,4) """ data = np.random.randn(8,4) data array([[-3.76909668e-01, -3.93537488e-01, -1.54879537e+00, 2.61747689e-01], [-1.35115615e+00, -1.16398850e+00, -1.84465321e-01, -1.40143679e+00], [-2.38693890e-01, -4.69138164e-01, -6.58391869e-01, -4.44785435e-04], [-6.51396461e-02, -3.32755829e-01, 5.05514006e-01, -1.00401128e-01], [ 3.54565932e-02, -1.80942509e+00, 1.46721963e+00, 2.11279327e+00], [ 2.70939217e-01, 3.55700759e-01, -5.81756627e-01, -2.47407404e-01], [ 2.47808394e-01, -2.05479810e-01, -7.55638923e-01, 3.65503977e-01], [ 1.14316952e+00, 3.04048072e-01, 7.47009462e-01, 8.08582657e-01]]) data.shape out : (8, 4) """ # 요소가 b 인 항목에 대한 mask 생성 names_b_mask = (names == 'b') names_b_mask """ out : array([False, True, False, False, False, False, False, False]) """ data[names_b_mask,:] """ array([[-1.35115615, -1.1639885 , -0.18446532, -1.40143679]]) """ # 요소가 'a'인 행의 데이터만 꺼내기 data[names == 'a',:] array([[-0.37690967, -0.39353749, -1.54879537, 0.26174769]]) # a 또는 c인 행의 데이터만 꺼내기 data[(names == 'a') | (names == 'c'), :] """ out : array([[-3.76909668e-01, -3.93537488e-01, -1.54879537e+00, 2.61747689e-01], [-2.38693890e-01, -4.69138164e-01, -6.58391869e-01, -4.44785435e-04]]) """ # 먼저 마스크를 만든다. # data array에서 0번째 열이 0보다 작은 요소의 boolean 값은 다음과 같다. data[:,0] <0 """ out : array([ True, True, True, True, False, False, False, False]) """ # 위의 마스크를 이용하여 0번째 열의 값이 0보다 작은 행을 구한다. data[data[:,0]<0,:] """ array([[-3.76909668e-01, -3.93537488e-01, -1.54879537e+00, 2.61747689e-01], [-1.35115615e+00, -1.16398850e+00, -1.84465321e-01, -1.40143679e+00], [-2.38693890e-01, -4.69138164e-01, -6.58391869e-01, -4.44785435e-04], [-6.51396461e-02, -3.32755829e-01, 5.05514006e-01, -1.00401128e-01]]) """ # 0번째 열의 값이 0보다 작은 행의 2,3번째 열 값 data[data[:,0]<0,2:4] """ out : array([[-1.54879537e+00, 2.61747689e-01], [-1.84465321e-01, -1.40143679e+00], [-6.58391869e-01, -4.44785435e-04], [ 5.05514006e-01, -1.00401128e-01]]) """ data[data[:,0]<0,2:4] = 0 """ out : array([[-0.37690967, -0.39353749, 0. , 0. ], [-1.35115615, -1.1639885 , 0. , 0. ], [-0.23869389, -0.46913816, 0. , 0. ], [-0.06513965, -0.33275583, 0. , 0. ], [ 0.03545659, -1.80942509, 1.46721963, 2.11279327], [ 0.27093922, 0.35570076, -0.58175663, -0.2474074 ], [ 0.24780839, -0.20547981, -0.75563892, 0.36550398], [ 1.14316952, 0.30404807, 0.74700946, 0.80858266]]) """
7. numpy 함수
7-1 하나의 array에 적용되는 함수This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters# 난수 생성 arr_rand = np.random.randn(5,3) arr_rand """ out : array([[ 0.19505464, 1.3236669 , 1.12034634], [-0.63740229, -0.12788398, 1.31366624], [ 0.44136668, -1.34736515, -1.12404818], [-0.72501746, 0.877711 , 0.66628103], [-0.1487842 , 0.86583231, -0.04592599]]) """ # 각 성분의 절댓값 구하기 np.abs() np.abs(arr_rand) """ out : array([[0.19505464, 1.3236669 , 1.12034634], [0.63740229, 0.12788398, 1.31366624], [0.44136668, 1.34736515, 1.12404818], [0.72501746, 0.877711 , 0.66628103], [0.1487842 , 0.86583231, 0.04592599]]) """ # 각 성분의 제곱근 계산 , np.sqrt() np.sqrt(arr_rand) """ out : array([[0.44164991, 1.15050724, 1.05846414], [ nan, nan, 1.1461528 ], [0.66435434, nan, nan], [ nan, 0.93686231, 0.81626039], [ nan, 0.93050111, nan]]) """ #nan 이 있는 곳은 음수 인 곳이다. #각 성분의 제곱 계산하기 np.square(arr_rand) np.square(arr_rand) """ out: array([[0.03804631, 1.75209407, 1.25517593], [0.40628168, 0.01635431, 1.72571898], [0.19480455, 1.81539284, 1.26348432], [0.52565031, 0.77037659, 0.44393041], [0.02213674, 0.74966558, 0.0021092 ]]) """ # 각 성분을 무리수 e의 지수로 삼은 값을 계산하기 , np.exp() --e^x np.exp(arr_rand) """ out : np.exp(arr_rand) array([[1.2153774 , 3.75717334, 3.06591588], [0.52866396, 0.87995546, 3.71978636], [1.55483073, 0.25992422, 0.32496162], [0.48431611, 2.40538746, 1.94698306], [0.86175506, 2.37698364, 0.95511265]]) """ #각 성분을 자연로그, 상용로그 , 밑이 2인 로그를 씌운 값, 2말고 다른 값을 지원하지 않고 오류가 뜬다 np.log(arr_rand) """ out: array([[-1.63447554, 0.28040584, 0.11363787], [ nan, nan, 0.27282188], [-0.81787927, nan, nan], [ nan, -0.1304379 , -0.40604373], [ nan, -0.14406403, nan]]) """ np.log10(arr_rand) """ out : array([[-0.70984371, 0.12177871, 0.0493523 ], [ nan, nan, 0.11848504], [-0.35520045, nan, nan], [ nan, -0.05664846, -0.17634255], [ nan, -0.06256621, nan]]) """ np.log2(arr_rand) """ out : array([[-2.35804975, 0.40454012, 0.16394479], [ nan, nan, 0.39359878], [-1.17995036, nan, nan], [ nan, -0.18818211, -0.58579728], [ nan, -0.20784046, nan]]) """ #각 성분의 부호 계산 (+인 경우 1, -인 경우 -1, 0인 경우 0) np.sign(arr_rand) """ out : array([[ 1., 1., 1.], [-1., -1., 1.], [ 1., -1., -1.], [-1., 1., 1.], [-1., 1., -1.]]) """ # 각 성분의 소수 첫 번째 자리에서 '올림'하기 np.ceil() np.ceil(arr_rand) """ out : array([[ 1., 2., 2.], [-0., -0., 2.], [ 1., -1., -1.], [-0., 1., 1.], [-0., 1., -0.]]) """ # 각 성분의 소수 첫번째 자리에서 '내림'하기 np.floor() np.floor(arr_rand) """ out : array([[ 0., 1., 1.], [-1., -1., 1.], [ 0., -2., -2.], [-1., 0., 0.], [-1., 0., -1.]]) """ # 각 성 분이 Nan인 경우 True를, 아닌 경우 False를 반환하기 np.isnan() np.isnan(np.log10(arr_rand)) """ out : array([[False, False, False], [ True, True, False], [False, True, True], [ True, False, False], [ True, False, True]]) """ # 각 성분이 무한대인 경우 True, 아닌 경우 False반환 np.isinf() np.isinf(arr_rand) #각 성분에 대한 삼각함수 값을 계산하기 (cos, cosh, sin sinh, tan, tanh) ,{np.cos(),np.tan()--np.삼각함수(array가 저장된 변수명)} np.cos(arr_rand) np.tan(arr_rand) 7-2 두 개의 array 적용되는 함수
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersarr1 =np.random.randn(5,3) arr2 =np.random.randn(5,3) """ out : arr1 = array([[ 1.76522743, -0.29958594, -2.00912102], [-0.70088572, -0.51860977, -1.27206332], [-1.85470839, 0.31652105, 0.88744675], [-1.40854267, -1.96998589, -0.66297333], [-0.26860916, -1.33627601, 0.55779865]]) arr2 = array([[-0.67834356, 0.69927473, -0.82387579], [ 0.04902886, 1.84169118, 0.07512269], [ 0.10003497, 0.58751203, 2.25762937], [-0.54050911, 0.28141563, 0.73981879], [-2.11927792, 0.81372656, 1.93494325]]) """ # 두 개의 array에 대해 동일한 위치의 성분끼리 연산 값을 계산하기(add, subtract, multiply, divide np.add(arr1,arr2) """ out : array([[ 1.08688387, 0.39968878, -2.83299681], [-0.65185686, 1.32308141, -1.19694064], [-1.75467342, 0.90403308, 3.14507613], [-1.94905178, -1.68857026, 0.07684546], [-2.38788709, -0.52254945, 2.4927419 ]]) """ np.multiply(arr1,arr2) """ out : array([[-1.19743065, -0.20949288, 1.65526616], [-0.03436363, -0.95511904, -0.09556081], [-0.18553569, 0.18595992, 2.00352585], [ 0.76133015, -0.55438483, -0.49048013], [ 0.56925747, -1.08736328, 1.07930873]]) """ 7-3. 통계 함수
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersarr1 = np.array([[ 1.76522743, -0.29958594, -2.00912102], [-0.70088572, -0.51860977, -1.27206332], [-1.85470839, 0.31652105, 0.88744675], [-1.40854267, -1.96998589, -0.66297333], [-0.26860916, -1.33627601, 0.55779865]]) # 전체 성분의 합 np.sum(arr1) """ out : -8.774367340000001 """ #열의 합 계산, array의 표현상 가로의 합, 실제로 열이다 np.sum(arr1, axis = 1) """ out : array([-0.54347953, -2.49155881, -0.65074059, -4.04150189, -1.04708652]) """ #행간 의 합 계산, array의 표현상 세로의 합, 실제로 행이다 np.sum(arr1, axis = 0) """ out : array([-2.46751851, -3.80793656, -2.49891227]) """ # 전체 성분의 평균 계산 np.mean(arr1) """ out : -0.5849578226666667 """ # 행 간의 평균을 계산 np.mean(arr1, axis=0) """ out : array([-0.4935037 , -0.76158731, -0.49978245]) """ # 열 간의 평균을 계산 np.mean(arr1, axis=1) """ out : array([-0.18115984, -0.8305196 , -0.21691353, -1.3471673 , -0.34902884]) """ # 전체 성분의 표준편차, 분산, 최소값, 최대값 계산(std, var, min, max) np.std(arr1) """ out : 1.0735933077541118 """ # 열 간의 표준편차 np.std(arr1, axis=1) """ out : array([1.54314508, 0.32096393, 1.18131792, 0.53534765, 0.77534087]) """ # 전체 성분의 최소값, 최대값이 위치한 인덱스를 반환(argmin, argmax) np.argmin(arr1) """ out : 2 """ # 각 행마다 최댓값이 위치한 인덱스 번호 np.argmax(arr1,axis=0) """ out : array([0, 2, 2]) """ # 맨 처음 성분부터 각 성분까지의 누적합 또는 누적곱을 계산(cumsum, cumprod) #누적합 np.cumsum(arr1) """ out : array([ 1.76522743, 1.46564149, -0.54347953, -1.24436525, -1.76297502, -3.03503834, -4.88974673, -4.57322568, -3.68577893, -5.0943216 , -7.06430749, -7.72728082, -7.99588998, -9.33216599, -8.77436734]) """ #누적곱 np.cumprod(arr1) """ out : array([ 1.76522743, -0.52883732, 1.06249817, -0.7446898 , 0.3862034 , -0.49127519, 0.91117221, 0.28840518, 0.25594424, -0.36050839, 0.71019644, -0.4708413 , 0.12647229, -0.16900188, -0.09426902]) """ #열 마다 누적합 np.cumsum(arr1,axis=1) """ out : array([[ 1.76522743, 1.46564149, -0.54347953], [-0.70088572, -1.21949549, -2.49155881], [-1.85470839, -1.53818734, -0.65074059], [-1.40854267, -3.37852856, -4.04150189], [-0.26860916, -1.60488517, -1.04708652]]) """ 7-4 벡터 관련 함수
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersx = [8,3,6,6,9,4,3,9,4,5] y = [5,4,5,8,2,3,7,8,5,1] np.cov(x,y) """ out : array([[5.34444444, 0.48888889], [0.48888889, 5.73333333]]) """ #상관 계수 구하기 np.corrcoef(x,y) """ out : array([[1. , 0.08831923], [0.08831923, 1. ]]) """ #대각 행렬을 기준으로 원하는 부분의 삼각 행렬을 얻을 수 있다. np.tril(np.corrcoef(x,y)) """ array([[1. , 0. ], [0.08831923, 1. ]]) """ 7-5 기타함수
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters# 전체 성분에 대해서 오름차순으로 정렬 np.sort(arr1) """ out : array([[-2.00912102, -0.29958594, 1.76522743], [-1.27206332, -0.70088572, -0.51860977], [-1.85470839, 0.31652105, 0.88744675], [-1.96998589, -1.40854267, -0.66297333], [-1.33627601, -0.26860916, 0.55779865]]) """ # 전체 성분에 대해서 내림차순으로 정렬 np.sort(arr1)[::-1] """ out : array([[-1.33627601, -0.26860916, 0.55779865], [-1.96998589, -1.40854267, -0.66297333], [-1.85470839, 0.31652105, 0.88744675], [-1.27206332, -0.70088572, -0.51860977], [-2.00912102, -0.29958594, 1.76522743]]) """ # 행 방향으로 오름차순으로 정렬 np.sort(arr1,axis=0) """ out : array([[-1.85470839, -1.96998589, -2.00912102], [-1.40854267, -1.33627601, -1.27206332], [-0.70088572, -0.51860977, -0.66297333], [-0.26860916, -0.29958594, 0.55779865], [ 1.76522743, 0.31652105, 0.88744675]]) """ 수업 내용 요약
스칼라 : 우리가 흔히 생각하는 숫자, 속력과 같은 느낌, 크기를 나타냄
벡터 : 방향을 나타내는 수 혹은 기호, 속도와 같은 느낌, 크기와 방향을 나타냄
3D 벡터
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersfrom mpl_toolkits.mplot3d import Axes3D import numpy as np yellow = [.4, .6, .5] red = [.11, .12, .3] blue = [.1, .7, .4] vectors = np.array([[0, 0, 0, .5, .5, .5], [0, 0, 0, .2, .1, .0], [0, 0, 0, .1, .3, .3]]) X, Y, Z, U, V, W = zip(*vectors) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.quiver(X, Y, Z, U, V, W, length=1) ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) ax.set_zlim([0, 1]) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show() 벡터의 크기
|v|(벡터의 크기)-(Magnitude, Norm, Length) = √(a^2+b^2+c^2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersdef L2_norm(v): L2_v_norm = v*v L2_v_norm = np.sum(L2_v_norm) L2_v_norm = np.sqrt(L2_v_norm) return L2_v_norm This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters# L1_Norm |v|=|x0|+|x1|+...+|xn| 벡터의 합 def L1_Norm(v): L1_v_norm = np.abs(v) L1_v_norm = np.sum(L1_v_norm) return L1_v_norm 벡터의 내적 (Dot Product)
두 벡터 a⃗ 와 b⃗ 의 내적은, 각 구성요소를 곱한 뒤 합한 값과 같습니다.
v = [1, 2, 3, 4]
x = [5, 6, 7, 8]
v ⋅ x = 1 * 5 + 2 * 6 + 3 * 7 + 4 * 8
= 70
- 내적은 교환법칙이 적용 됩니다: a⋅b=b⋅a
- 내적은 분배법칙이 적용 됩니다: a⋅(b+c)=a⋅b+a⋅c
- 벡터의 내적을 위해서는 두 벡터의 길이가 반드시 동일해야 합니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersa = np.array([1,2,3,4,5]) b = np.array([2,4,6,8,10]) print (sum(a*b)) 두 벡터 간의 거리
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersa = np.array([1,2,3,4,5]) b = np.array([2,4,6,8,10]) print(np.sum((a-b)**2)**(1/2)) print(np.sqrt(np.sum((a-b)**2))) """ out : 7.416198487095663 7.416198487095663 """ 행렬의 Transpose (3,2) --> (2,3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersA = np.array([[1,2,3],[4,5,6]]) """ out : array([[1, 2, 3], [4, 5, 6]]) """ A.T """ array([[1, 4], [2, 5], [3, 6]]) """ 역행렬
- 역행렬을 계산하는 방법은 여러가지가 있으며, 행렬의 역수 와 같이 표현 할 수 있습니다.
- 즉 행렬과 그 역행렬의 값은 항상 1 (단위 매트릭스) 입니다. 2x2 매트릭스를 기준으로, 역행렬을 계산하는 방식중 하나는 아래와 같습니다.
역행렬 역행렬의 조건
det( A ) = │A│≠0
ad-bc ≠ 0
*, np.dot, np.matmul 에 대해서
* : shape이 동일한 두 행렬의 원소 끼리 곱하는 연산자이다.
np.dot : 두 벡터의 내적, 내적곱, 점곱 등을 계산하는 함수이다.
np.matmul : 행렬의 곱연산을 위해 정의된 함수이다. (@)
np.dot과 np.matmul의 차이점
1. dot은 행렬과 상수의 곱셈을 혀옹하지만, matmul은 Error를 일으킨다.
2. 3차원 이상의 행렬곱을 수행할 경우, dot와 matmul은 전혀 다른 결과를 나타낸다.
참조 : https://cyber0946.tistory.com/64
Python @연산자, 벡터 행렬 곱연산
파이썬의 Numpy, Tensorflow는 행렬 곱을 빠르게 계산할 수 있도록 함수를 지원한다. 하지만 두 실수의 곱연산과 달리 matrix의 곱연산은 교환법칙(commutative law)가 성립하지 않는다. 즉, 편리한 함수를
cyber0946.tistory.com
결론
벡터 계산할 때는 dot, 행렬 계산할 떄는 matmul을 사용한다
Errors
MSE:평균 제곱 오차(Mean squared error ), 차의 제곱에 대해 평균을 취한 것
MAE: Mean Square Error, 에러를 제곱하여 평균을 계산하니, 값은 낮을수록 좋다.This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters# MSE def MSE(x, y): return np.mean(np.square(x-y)) # MAE def MAE(x, y): return np.mean(np.abs((x - y))) #error 타입(MSE, MAE)마다 값이 다르게 나오게 하는 함수 def error(x, y, type) : if type == 'MSE': a = np.mean(np.square(x-y)) if type == 'MAE': a = np.mean(np.abs((x - y))) return a '파이썬(판다스, AI,데이터 분석)' 카테고리의 다른 글
판다스 replace (0) 2021.06.05 판다스 인덱싱 (0) 2021.06.04 파이썬 판다스 inplace 옵션 (2) 2021.05.18 판다스(파이썬), 데이터 프레임, 행과 열 (0) 2021.05.18 판다스 한글 파일이 깨질 때 (0) 2021.05.15