일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- 성능지표
- PyQt5
- 사이트 도메인
- Django
- 콘솔 가상환경 # 콘솔 #가상환경
- #ifdef
- 튜토리얼
- 명령어
- href
- bootstrap4 패키지
- flask
- #else
- #undef
- VS Code
- #ifndef
- Action
- javascript
- DB 데이터
- 실시간 시계
- #if
- openweathermap
- 환경변수 설정
- heroku
- DB 데이터 저장
- #endif
- jinja2
- bootstrap
- OpenCV
- OpenCV + Flask
- MySQL 세팅
- Today
- Total
PROGRAMMING
Python 4 본문
Numpy install, dtype=' ', dtype, astype, numpy.ndarray, ndarray function, indexing(transpose, flat), 넘파이 배열 원소 접근방법(timeit), 배열 생성 및 shape 반환(zeros, ones, empty), np.random.random(randint), 인덱싱, 연속원소 배열 생성함수, np.linspace(), reshape & -1, ravel, newaxis, hstack / vstack, column_stack / row_stack, concatenate, hsplit / vsplit, 각 원소에 접근, 행의 slicing, 브로드캐스팅, vectorize, 평균-분산-표준편차, 전치행렬(Transpose), inverse matrix
Numpy 설치¶
- 파이썬으로 수치계산을 하기 위한 라이브러리
- 다차원 배열을 효율적으로 구현한 Numpy, 배열간 빠른 연산을 할 수 있는 루틴 제공
numpy 미설치시 필요한 문구
pip install numpy - normal
conda install numpy - for anaconda
numpy 패키지 업데이트
pip install numpy --upgrade
numpy 패키지 제거
pip uninstall numpy
- #### 리스트: 여러 데이터 타입의 원소를 가질 수 있음
- #### Numpy: 단일 데이터 타입의 원소를 가짐
import numpy as np
A = np.array([1,2,3])
print(A)
print(len(A))
print(A.dtype)
print(type(A))
print(type(A[0]))
[1 2 3]
3
int32
<class 'numpy.ndarray'>
<class 'numpy.int32'>
A = [1,2,3]
B = [-1,-2,-3]
C = []
for a,b in zip(A,B):
C.append(a+b)
print(C)
[0, 0, 0]
import numpy as np
A = np.array([1,2,3])
B = np.array([-1,-2,-3])
C = A+B # vectorization
print(C)
[0 0 0]
import numpy as np
a = np.array([0.1,0.2,0.3])
print(a)
print(a.dtype)
print(type(a[0]))
[0.1 0.2 0.3]
float64
<class 'numpy.float64'>
dtype=' ', dtype, astype, numpy.ndarray¶
c = np.array([1,2,3], dtype=np.float64)
print(c)
print(c.dtype)
[1. 2. 3.]
float64
dtype
d = np.array([1.1, 2.2, 3.3, 4.7])
print(d.dtype)
float64
astype
e = d.astype(np.int32)
print(e.dtype)
print(e)
int32
[1 2 3 4]
numpy.ndarray
A = np.array([[1,2,3],[4,5,6]])
print(A)
print(type(A))
[[1 2 3]
[4 5 6]]
<class 'numpy.ndarray'>
A = np.array([[1,2,3],[4,5,6]])
print(A.ndim)
print(A.shape)
print(A.size)
2
(2, 3)
6
import numpy as np
B = np.array([ [ [ [3,0],[4,5] ], [ [6,7],[8,9] ] ],[ [ [0,-5],[4,5] ],[ [6,-9],[-2,-3] ] ] ])
print(B.ndim)
print(B.shape)
print(B.size)
C = np.array([ [ [1,2,3],[4,5,6] ],[ [1,2,3],[4,5,6] ] ])
print(C.ndim)
4
(2, 2, 2, 2)
16
3
b = np.array([1,2,3,4,5,6])
print(b.max(), end= " ")
print(b.min(), end= " ")
print(b.sum(), end= " ")
print(b.mean(), end= " ")
6 1 21 3.5
c = np.array([[1,2,3],[4,5,6]])
print(c)
print(c.shape)
[[1 2 3]
[4 5 6]]
(2, 3)
c.sum(axis = 0) # 열방향으로 계산
array([5, 7, 9])
c.sum(axis = 1) # 행방향으로 계산
array([ 6, 15])
인덱싱¶
import numpy as np
A = np.arange(0,15,2)
print(A.shape)
print(A)
(8,)
[ 0 2 4 6 8 10 12 14]
for i in range(A.size):
#print(A[i], end=" ")
print("A[{0:}] : {1:} ".format(i,A[i]))
A[0] : 0
A[1] : 2
A[2] : 4
A[3] : 6
A[4] : 8
A[5] : 10
A[6] : 12
A[7] : 14
for i in range(A.size):
print("A[{0:}] : {1:} ".format(i-8,A[i-8]))
# 역순 출력
#for i in range(A.size):
# print("A[{0:}] : {1:} ".format(-(i+1),A[-(i+1)]))
A[-8] : 0
A[-7] : 2
A[-6] : 4
A[-5] : 6
A[-4] : 8
A[-3] : 10
A[-2] : 12
A[-1] : 14
import numpy as np
A = np.arange(12).reshape(3,4)
#print(A)
#print(A.ndim) # 2
# ★★★
print(A.shape, A.shape[0], A.shape[1])
# 직접 접근
for i in range(A.shape[0]):
for j in range(A.shape[1]):
print("A[{0:}][{1:}] : {2:},".format(i,j,A[i][j]), end= ' ')
print()
# 행 접근
for i in range(A.shape[0]):
print("A[{0:}] : {1:}".format(i,A[i]))
(3, 4) 3 4
A[0][0] : 0, A[0][1] : 1, A[0][2] : 2, A[0][3] : 3,
A[1][0] : 4, A[1][1] : 5, A[1][2] : 6, A[1][3] : 7,
A[2][0] : 8, A[2][1] : 9, A[2][2] : 10, A[2][3] : 11,
A[0] : [0 1 2 3]
A[1] : [4 5 6 7]
A[2] : [ 8 9 10 11]
import numpy as np
A = np.arange(9).reshape(3,3)
print(A)
i = 0
for row in A:
print("A[{0:}] : {1:}".format(i,A[i])) # or format(i,row)
i += 1
[[0 1 2]
[3 4 5]
[6 7 8]]
A[0] : [0 1 2]
A[1] : [3 4 5]
A[2] : [6 7 8]
transpose
import numpy as np
A = np.arange(9).reshape(3,3)
print(A)
#print(A.T)
for column in A.T:
print("{}".format(column))
[[0 1 2]
[3 4 5]
[6 7 8]]
[0 3 6]
[1 4 7]
[2 5 8]
flat
import numpy as np
A = np.arange(9).reshape(3,3)
for a in A.flat: # 전치행렬의 개별출력 : for a in A.T.flat:
print(a, end= ' ')
0 1 2 3 4 5 6 7 8
import numpy as np
A = np.arange(0,20,2)
print(A[0:3])
print(A[:3])
print(A[7:10])
print(A[7:])
print(A[:])
print(A[::2]) # step = 2
print(A[:-2]) # 마지막 2개 원소 제외
print(A[-2:]) # 마지막 2개 원소만 추출
print(A[0:3].shape)
print(A[0:3].ndim)
[0 2 4]
[0 2 4]
[14 16 18]
[14 16 18]
[ 0 2 4 6 8 10 12 14 16 18]
[ 0 4 8 12 16]
[ 0 2 4 6 8 10 12 14]
[16 18]
(3,)
1
넘파이 배열 원소 접근방법¶
A = np.array([1,2,3])
print(A.shape)
for i in range(A.size):
print(A[i])
(3,)
1
2
3
B = np.array([[1,2,3],[4,5,6]])
print(B[0])
print(B[1])
print(B[0,2])
[1 2 3]
[4 5 6]
3
C = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
print(C[1,0,2])
9
# arange, reshape
import numpy as numpy
C = np.arange(24).reshape(2,3,4)
print(C)
print(C.shape)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
(2, 3, 4)
import numpy as numpy
a = np.array([1,2,3,4]) # tuple
print(a.shape)
(4,)
a.shape = 1,4
print(a)
print(a.shape)
print()
a.shape = 4,1
print(a)
print(a.shape)
[[1 2 3 4]]
(1, 4)
[[1]
[2]
[3]
[4]]
(4, 1)
import sys
np.set_printoptions(threshold=10)
np.set_printoptions()
print(np.arange(10000).reshape(100,100))
[[ 0 1 2 ... 97 98 99]
[ 100 101 102 ... 197 198 199]
[ 200 201 202 ... 297 298 299]
...
[9700 9701 9702 ... 9797 9798 9799]
[9800 9801 9802 ... 9897 9898 9899]
[9900 9901 9902 ... 9997 9998 9999]]
timeit: 실행 시간 측정
import timeit
timeit.timeit('B**2', setup='import numpy as np; B=np.arange(100)')
0.8073218000000679
timeit.timeit('[i**2 for i in A]', setup='A=range(100)')
25.62654550000002
배열 생성 및 shape 반환¶
zeros
import numpy as numpy
A = np.zeros((2,3))
print(A)
print(A.dtype)
[[0. 0. 0.]
[0. 0. 0.]]
float64
import numpy as numpy
A = np.zeros((2,3), dtype = 'uint8')
print(A)
print(A.dtype)
A = A.astype(np.float64)
print(A.dtype)
[[0 0 0]
[0 0 0]]
uint8
float64
ones
import numpy as numpy
A = np.ones((2,3), dtype = 'uint8')
print(A)
print(A.dtype)
[[1 1 1]
[1 1 1]]
uint8
empty
C = np.empty((5,5))
print(C)
print(C.dtype)
[[1.24115177e-303 4.67296746e-307 1.69121096e-306 1.33511969e-306
1.89146896e-307]
[7.56571288e-307 4.00544531e-307 1.11261095e-306 3.56043054e-307
1.37961641e-306]
[2.22518251e-306 1.33511969e-306 1.69118108e-306 8.06632139e-308
1.20160711e-306]
[1.69119330e-306 1.78022342e-306 2.04721734e-306 1.69118108e-306
1.69111725e-306]
[1.69118923e-306 1.11260144e-306 6.89812281e-307 2.22522596e-306
2.59854240e-306]]
float64
import random
import numpy as np
D = np.random.random((3,3))
print(D)
[[0.80012447 0.56383579 0.1883487 ]
[0.38382225 0.3097761 0.26248477]
[0.55870293 0.38478432 0.79158559]]
import random
import numpy as numpy
E = np.random.randint(1,10,(2,3))
print(E)
[[4 8 1]
[3 7 1]]
연속원소 배열 생성함수¶
- np.arange(시작, 마지막, 간격)
- np.arange(시작, 마지막)
- np.arange(마지막)
## np.linspace() : 지정한 범위 내에서 원하는 원소 개수로 숫자를 뽑아냄 - np.linspace(시작값, 마지막값, 샘플 개수)
- np.linspace(시작값, 마지막값)
import numpy as numpy
A = np.arange(0,100,5)
print(A)
B = np.arange(0.1,2.5,0.1)
print(B)
C = np.arange(10)
print(C)
[ 0 5 10 ... 85 90 95]
[0.1 0.2 0.3 ... 2.2 2.3 2.4]
[0 1 2 3 4 5 6 7 8 9]
import random as rd
import matplotlib.pyplot as plt
%matplotlib inline
# 샘플값을 정하지 않으면 기본적으로 50개를 뽑아냄
x = np.linspace(0,10,11)
num = len(x)
y1 = (2*x+.5)
y2 = np.zeros(num)
rd.seed()
for i in range(0,num):
noise = rd.uniform(-3,3)
y2[i] = y1[i] + noise
plt.scatter(x, y1, c='black', s=80)
plt.scatter(x, y2, c='red', s=80)
plt.show()
print(x)
print(y2)
print(x.size) # = print(num)
[ 0. 1. 2. ... 8. 9. 10.]
[ 2.30919937 3.22597329 2.77261832 ... 17.4469999 18.63426023
19.08139476]
11
A = np.arange(16)
B = A.reshape(4,4)
print(A)
print(B)
print(B.shape)
print(B.base)
print(B.base is A) # B가 배열 A의 데이터가 저장된 공간을 공유
[ 0 1 2 ... 13 14 15]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
(4, 4)
[ 0 1 2 ... 13 14 15]
True
C = B.reshape(2,8).copy()
C[0] = 0
print(C)
print(B)
[[ 0 0 0 ... 0 0 0]
[ 8 9 10 ... 13 14 15]]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
reshape & -1
C = np.arange(16)
print(C)
D = C.reshape(8,-1)
# 모르겠을 때는 -1를 넣으면 알아서 계산, 단 1번만 사용해야 계산을 해줌
print(D)
E = C.reshape(-1,8)
print(E)
[ 0 1 2 ... 13 14 15]
[[ 0 1]
[ 2 3]
[ 4 5]
...
[10 11]
[12 13]
[14 15]]
[[ 0 1 2 ... 5 6 7]
[ 8 9 10 ... 13 14 15]]
ravel()¶
- 주어진 배열을 1차원 배열로 변환하여 리턴
#### newaxis() - 차원을 증가시킴
#### hstack / vstack - 결합함수
- hstack : 가로 결합
- vstack : 세로 결합
#### column_stack, row_stack
#### concatenate() - 지정한 방향으로 배열 결합
- axis = 0 : 열방향, = 1 : 행방향 #### hsplit / vsplit (horizontally column-wise, vertically rows-wise)
- 가로 또는 세로로 자르기
A = np.array([[1,2],[3,4]])
B = A.ravel()
print(B)
print(B.shape)
print(B.ndim)
print(B.base)
print(B.base is A)
[1 2 3 4]
(4,)
1
[[1 2]
[3 4]]
True
a = np.array([1,2,3])
a = a[:,np.newaxis] # 열 증가
print(a.shape)
print(a)
a = a[np.newaxis,:] # 행 증가
print(a.shape)
print(a)
(3, 1)
[[1]
[2]
[3]]
(1, 3, 1)
[[[1]
[2]
[3]]]
import numpy as np
A = np.array([[1,2],[3,4]])
B = np.array([[1,0],[1,0]])
print(A)
print(B)
C = np.hstack((A,B)) # horizontally stack
print(C)
D = np.vstack((B,A)) # vertically stack
print(D)
[[1 2]
[3 4]]
[[1 0]
[1 0]]
[[1 2 1 0]
[3 4 1 0]]
[[1 0]
[1 0]
[1 2]
[3 4]]
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.array([7,8,9])
D = np.column_stack((a,b,c))
print(D)
E = np.row_stack((a,b,c))
print(E)
[[1 4 7]
[2 5 8]
[3 6 9]]
[[1 2 3]
[4 5 6]
[7 8 9]]
import numpy as np
A = np.array([[1,2],[3,4]])
B = np.array([[1,0],[0,1]])
C = np.concatenate((A,B), axis=0)
D = np.concatenate((A,B), axis=1)
print(C)
print(D)
[[1 2]
[3 4]
[1 0]
[0 1]]
[[1 2 1 0]
[3 4 0 1]]
A = np.arange(18).reshape(3,-1)
print(A)
B = np.hsplit(A, 3)
print(B)
b = np.hsplit(A, (2,3)) # horizontally-split : 접근방향이 수평, 수평방향으로 조건만큼 간 다음 자름
print(b)
# (2,4) 수평으로 2번째 자리 읽고 자르고 뒤부터 4번째 자리 읽고 자름
# (2,3) 수평으로 앞에 2개 뒤에 3개 묶고 중간에 1 놔둠
c = np.vsplit(A, (1,2)) # vertically-split : 접근방향이 수직, 수직방향으로 조건만큼 간 다음 자름
print(c) # (1,2) 수직으로 1번째 자리 읽고 자르고 뒤부터 2번째 자리 읽고 자름
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]]
[array([[ 0, 1],
[ 6, 7],
[12, 13]]), array([[ 2, 3],
[ 8, 9],
[14, 15]]), array([[ 4, 5],
[10, 11],
[16, 17]])]
[array([[ 0, 1],
[ 6, 7],
[12, 13]]), array([[ 2],
[ 8],
[14]]), array([[ 3, 4, 5],
[ 9, 10, 11],
[15, 16, 17]])]
[array([[0, 1, 2, 3, 4, 5]]), array([[ 6, 7, 8, 9, 10, 11]]), array([[12, 13, 14, 15, 16, 17]])]
각 원소에 접근¶
A[row][col] or A[row,col]
import numpy as np
A = np.arange(1,13).reshape(3,4)
for i in range(A.shape[0]):
for j in range(A.shape[1]):
print("A[{0:}][{1:}] : {2:2d} or A[{3:},{4:}] : {5:2d}".format(i,j,A[i][j],i,j,A[i,j]))
A[0][0] : 1 or A[0,0] : 1
A[0][1] : 2 or A[0,1] : 2
A[0][2] : 3 or A[0,2] : 3
A[0][3] : 4 or A[0,3] : 4
A[1][0] : 5 or A[1,0] : 5
A[1][1] : 6 or A[1,1] : 6
A[1][2] : 7 or A[1,2] : 7
A[1][3] : 8 or A[1,3] : 8
A[2][0] : 9 or A[2,0] : 9
A[2][1] : 10 or A[2,1] : 10
A[2][2] : 11 or A[2,2] : 11
A[2][3] : 12 or A[2,3] : 12
행의 슬라이싱¶
- A[i] or A[i,:]
import numpy as np
A = np.arange(1,13).reshape(3,4)
for i in range(A.shape[0]):
print("A[{0:}] : {1:} or A[{2:},:] : {3:}".format(i,A[i],i,A[i,:]))
A[0] : [1 2 3 4] or A[0,:] : [1 2 3 4]
A[1] : [5 6 7 8] or A[1,:] : [5 6 7 8]
A[2] : [ 9 10 11 12] or A[2,:] : [ 9 10 11 12]
print(A)
print()
print(A[:2,:2])
A[:2,:2]=0
print(A)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[1 2]
[5 6]]
[[ 0 0 3 4]
[ 0 0 7 8]
[ 9 10 11 12]]
import numpy as np
A = np.arange(1,13).reshape(3,4)
for i in range(A.shape[0]):
print("A[{0:}] : {1:} or A[{2:},:] : {3:}".format(i,A[i],i,A[i,:]))
A[0] : [1 2 3 4] or A[0,:] : [1 2 3 4]
A[1] : [5 6 7 8] or A[1,:] : [5 6 7 8]
A[2] : [ 9 10 11 12] or A[2,:] : [ 9 10 11 12]
print(A); print()
print(A[:2,:2])
A[:2,:2]=0
print(A); print()
print(A[1:2])
print(A[:2][1]); print()
print(A[:,2])
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[1 2]
[5 6]]
[[ 0 0 3 4]
[ 0 0 7 8]
[ 9 10 11 12]]
[[0 0 7 8]]
[0 0 7 8]
[ 3 7 11]
print(A[0]) # 행 슬라이싱
print(A[:,1]) # 열 슬라이싱
print(A[...,1]) # 열 슬라이싱(...)
[0 0 3 4]
[ 0 0 10]
[ 0 0 10]
import numpy as np
A = np.array([1,4,6,8]).reshape(2,2)
B = np.array([2,2,2,2]).reshape(2,2)
print(A)
print(B)
print(A+B)
print(A-B)
print(A*B)
print(A/B)
print()
print(A@B) # 행렬곱셈
print(np.dot(A,B))
print(A.dot(B))
[[1 4]
[6 8]]
[[2 2]
[2 2]]
[[ 3 6]
[ 8 10]]
[[-1 2]
[ 4 6]]
[[ 2 8]
[12 16]]
[[0.5 2. ]
[3. 4. ]]
[[10 10]
[28 28]]
[[10 10]
[28 28]]
[[10 10]
[28 28]]
다른 크기의 배열간의 산술연산(브로드캐스팅)
¶
A.shape = (2,3,4,5)
B.shape = (5,) # B의 차원의 개수가 같아지도록 B shape 왼쪽에 1 추가
B.shape = (1,1,1,5)
- 두 배열을 비교
- 대응하는 차원이 같거'나' 한쪽이 1인 경우에만 브로드캐스팅 가능
A.shape = (2,1,3,1)
B.shape = (6,1,3)
# B.shape = (1,6,1,3)
# A, B 비교 : 2vs1, 1vs6, 3vs1, 1vs3 > 1이 4군데 다 있으므로 브로드캐스팅 가능
A.shape = (2,3,4)
B.shape = (3,1)
# B.shape = (1,3,1)
# A, B 비교 : 1vs2, 3vs3, 4vs1 > 1이 두군데, 같은 차원이 한군데이므로 브로드캐스팅 가능
import numpy as np
A = np.arange(10,130,10).reshape(3,4)
print(A)
print(A.shape)
B = np.arange(1,5)
# B 행렬을 브로드캐스팅조건화시키고자 첫 행의 [1,2,3,4]를 2줄 더 복사
print(B)
print(B.shape)
print(A+B)
print()
print(A.dot(B))
# 조건확인을 위해 (4,) 는 (1,4)가 되었지만 이것은 조건 확인을 위한 가시적인 것이고
# 실제로는 계산에 들어갈 때에는 행렬곱셈이 되면서 B가 (3,4)행렬이 아닌 (4,3)행렬로 변경시켜서 계산함
# (1 1 1)
# (2 2 2)
# (3 3 3)
# (4 4 4)
[[ 10 20 30 40]
[ 50 60 70 80]
[ 90 100 110 120]]
(3, 4)
[1 2 3 4]
(4,)
[[ 11 22 33 44]
[ 51 62 73 84]
[ 91 102 113 124]]
[ 300 700 1100]
vectorize
¶
- numpy 내장 함수
- Vectorize는 매트릭스 구조를 지닌 데이터의 연산을 일괄 처리할 수 있게 Series, DataFrame, array 등과 같이 sequence형 자료를 함수의 매개변수로 포함시킬 수 있게 하는 것
import numpy as np
matrix = np.arange(1,10).reshape(3,3)
print(matrix)
add_100 = lambda i: i+100
vectorized_add_100 = np.vectorize(add_100)
print(vectorized_add_100(matrix))
find_odd = lambda i: i if i%2==1 else 0
vectorized_find_odd = np.vectorize(find_odd)
print(vectorized_find_odd(matrix))
[[1 2 3]
[4 5 6]
[7 8 9]]
[[101 102 103]
[104 105 106]
[107 108 109]]
[[1 0 3]
[0 5 0]
[7 0 9]]
브로드캐스팅
¶
import numpy as np
matrix = np.arange(1,10).reshape(3,3)
print(matrix)
print()
print(np.max(matrix))
print(np.min(matrix))
print(np.max(matrix, axis=0))
print(np.max(matrix, axis=1))
print(np.min(matrix, axis=0))
print(np.min(matrix, axis=1))
print(np.mean(matrix, axis=0))
print(np.mean(matrix, axis=1))
print()
vector_column = np.max(matrix, axis=1, keepdims=True)
print(vector_column.shape)
print(matrix.shape) # 브로드캐스팅 가능
print()
print(vector_column)
print(matrix - vector_column)
[[1 2 3]
[4 5 6]
[7 8 9]]
9
1
[7 8 9]
[3 6 9]
[1 2 3]
[1 4 7]
[4. 5. 6.]
[2. 5. 8.]
(3, 1)
(3, 3)
[[3]
[6]
[9]]
[[-2 -1 0]
[-2 -1 0]
[-2 -1 0]]
평균 분산 표준편차
¶
- mean: 평균
- var: 분산 (variance)
- std: 표준편차 (standard deviation)
import numpy as np
matrix = np.arange(1,10).reshape(3,3)
print(matrix)
print()
print("평균: ",np.mean(matrix))
print("평균: ",np.mean(matrix, axis=0))
print()
print("분산: ",np.var(matrix))
print()
print("표준편차: ",np.std(matrix))
# 정확도 높은 표준편차, 모분모가 n이 아닌 n-1로 함
print("표준편차: ",np.std(matrix, ddof=1)) # ddof=k : n-(k)
[[1 2 3]
[4 5 6]
[7 8 9]]
평균: 5.0
평균: [4. 5. 6.]
분산: 6.666666666666667
표준편차: 2.581988897471611
표준편차: 2.7386127875258306
행렬의 전치(전치행렬, Transpose)
¶
import numpy as np
# 참고
print(np.array([[1,2,3,4,5,6]]).T.shape)
print(np.array([1,2,3,4,5,6]).shape)
print()
matrix = np.arange(1,10).reshape(3,3)
print(matrix)
print(matrix.T)
print()
# (6,)는 전치 불가, (6,1)은 전치 가능
print(np.array([[1,2,3,4,5,6]]).T)
(6, 1)
(6,)
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1 4 7]
[2 5 8]
[3 6 9]]
[[1]
[2]
[3]
[4]
[5]
[6]]
matrix = np.array([[1,1,1],[1,1,9],[1,1,15]])
print(matrix)
np.linalg.matrix_rank(matrix) # liinalg : linear algebra, 고유 행렬 개수 : rank
[[ 1 1 1]
[ 1 1 9]
[ 1 1 15]]
2
inverse matrix
¶
import numpy as np
matrix = np.array([[1,4],[2,5]])
print(matrix); print()
# 역행렬(inv : inverse)
inv_matrix = np.linalg.inv(matrix) # linalg : linear algebra
print(inv_matrix)
print(matrix @ inv_matrix)
[[1 4]
[2 5]]
[[-1.66666667 1.33333333]
[ 0.66666667 -0.33333333]]
[[1. 0.]
[0. 1.]]
matrix = np.arange(1,7).reshape(2,3)
inv_matrix = np.linalg.pinv(matrix) # pinv : 유사 역행렬
print(inv_matrix)
print()
print(matrix @ inv_matrix)
print(np.round(matrix @ inv_matrix)) # np.round
[[-0.94444444 0.44444444]
[-0.11111111 0.11111111]
[ 0.72222222 -0.22222222]]
[[ 1.00000000e+00 2.22044605e-16]
[-8.88178420e-16 1.00000000e+00]]
[[ 1. 0.]
[-0. 1.]]
from IPython.core.display import display, HTML display(HTML(""))
'Python > Numpy' 카테고리의 다른 글
Python numpy ipynb 코드블럭 (0) | 2020.12.14 |
---|---|
Python numpy 모듈 (0) | 2020.11.30 |