4Z1 - Artificial Intelligence/python for ML

MRP -112 : 1-2. 파이썬 Numpy - vector/ matrix 생성

Richrad Chung 2020. 9. 16. 13:52
머신런닝에서 많이 쓰이는 라이브러리 이므로 잘 알아두어야 한다.

vector/ matrix 생성
행렬곱(dot product)
broadcast
index / slice / iterator
concatenate
useful function(loadtxt(), rand(), argmax(), ....)


파이썬 Numpy 벡터 / 행렬 생성 

파이썬 Numpy 벡터 / 행렬 연산

 

numpy를 활용하면 reshape 가 탁월하다 ,

 

import numpy as np

# 리스트로 행렬 표현

A = [ [1, 0], [0, 1] ]
B = [ [1, 1], [1, 1] ] 

A + B    # 행렬 연산이 아닌 리스트 연산

print(" ========================================")

# numpy matrix, 직관적임

A = np.array([ [1, 0], [0, 1] ]) 
B = np.array([ [1, 1], [1, 1] ]) 

A + B    # 행렬 연산

print(" ========================================")

A = np.array([1, 2, 3]) 
B = np.array([4, 5, 6]) 

# vector A, B 출력
print("A ==", A, ", B == ", B)

# vector A, B 형상 출력 => shape
print("A.shape ==", A.shape, ", B.shape ==", B.shape)

# vector A, B 차원 출력 => ndim
print("A.ndim ==", A.ndim, ", B.ndim ==", B.ndim)

print(" ========================================")


# vector 산술 연산

print("A + B ==", A+B)  
print("A - B ==", A-B)
print("A * B ==", A*B)
print("A / B ==", A/B)

print(" ========================================")

A = np.array([ [1, 2 ,3], [4, 5, 6] ]) 
B = np.array([ [-1, -2, -3], [-4, -5, -6] ])

# matrix A, B 형상 출력 => shape
print("A.shape ==", A.shape, ", B.shape ==", B.shape)

# matrix A, B 차원 출력 => ndim
print("A.ndim ==", A.ndim, ", B.ndim ==", B.ndim)

print(" ========================================")

# vector 생성

C = np.array([1, 2, 3]) 

# vector C형상 출력 => shape
print("C.shape ==", C.shape) 

# vector를 (1,3) 행렬로 형 변환
C = C.reshape(1, 3)  

print("C.shape ==", C.shape)
print(" ========================================")