Vector representation of python

  • Vector를 파이썬으로 표현하는 다양한 방법 존재
vector_a = [1, 2, 10]  # List로 표현했을 경우
vector_b = (1, 2, 10)  # Tuple로 표현했을 경우
vector_c = {'x':1, 'y':2, 'z':10}  # dict로 표현했을 경우
  • 최선의 방법은 없고, 값의 변경 유무, 속성값 유무에 따라 선택가능

 

1. Vector 덧셈

Ex 1) 파이썬 답지 못한 벡터 표현 (X)

u = [2, 2]
v = [2, 3]
z = [3, 5]
result = []
for i in range(len(u)):
    result.append(u[i] + v[i] + z[i])
    
print(result)

 

 

Ex 2) zip을 사용하여 Ex 1) 표현 

u = [2, 2]
v = [2, 3]
z = [3, 5]

result = [sum(i) for i in zip(u,v,z)]
print(result)

[7, 10]

 

 

2. Vector 곱셈

Ex) Scalar-Vector Product

u = [1, 2, 3]
v = [4, 5, 6]
a = 5
result = [a * sum(z) for z in zip(u,v)]

print(result)

[25, 35, 45]

 

 

Matrix representation of python

  • Matrix도 파이썬으로 표현하는 다양한 방법 존재
matrix_a = [[3, 6], [4, 5]]  # List로 표현했을 경우
matirx_b = [(3, 6), (4, 5)]  # Tuple로 표현했을 경우
matrix_c = {(0, 0):3, (0, 1):6, (1, 0):4, (1, 1):5}  # dict로 표현했을 경우
  • dict 로 표현할 때는 무궁무진한 방법이 있음
  • 기본적으로 2-Dimensional List 형태로 표현함
  • [[1번째 row], [2번째 row], [3번째 row]]

 

1. Matrix 덧셈

Ex) List comprehension 사용

matrix_a = [[3, 6], [4, 5]]
matrix_b = [[5, 8], [6, 7]]
result = [[sum(row) for row in zip(*t)] for t in zip(matrix_a, matrix_b)]

print(result)

[[8,14], [10, 12]]

 

 

2. Matrix 곱셈(Scalar)

Ex) Scalar-Matrix Product

matrix_a = [[3,6], [4,5]]
alpha = 4
result = [[alpha * element for element in t] for t in matrix_a]

print(result)

[[12, 24], [16, 20]]

 

 

3. Matrix Transpose

Ex) List comprehension + zip

matrix_a = [[1, 2, 3], [4, 5, 6]]
result = [[row for row in t] for t in zip(*matrix_a)]

print(result)

 

 

4. Matrix Product

Ex) matrix_b에서 zip(*matrix_b)을 사용하여 column_b을 만들어줌

matrix_a = [[1, 2, 3], [4, 5, 6]]
matrix_b = [[1, 4], [2, 5], [3, 6]]
result = [[a * b for a, b in zip(row_a, column_b) for column_b in zip(*matrix_b)] for row_a in matrix_a]

print(result)

 

'✍🏻Language & FrameWork > Python' 카테고리의 다른 글

[Python for ML] Linear Algebra Codes - 2  (2) 2024.01.04
[Python for ML] News Categorization  (0) 2024.01.02
[Python for ML] Asterisk  (0) 2024.01.02
[Python for ML] Reduce 함수  (0) 2024.01.01
[Python for ML] Map 함수  (0) 2024.01.01

Asterisk(*)

  • 단순 곱셈, 제곱 연산, 가변 인자(여러 개 값들을 한 번에 받을 수 있음)등 다양하게 사용됨
  • tuple, dict 등의 자료형에 들어가 있는 값을 unpacking 하기 편리함
  • 함수의 입력값, zip 등에 유용하게 사용가능

 

Ex 1) 가변 인자 사용 예

  • a = 1, *args = (2, 3, 4, 5, 6)
  • 가변 인자는 Tuple 형태
def asterisk_test(a, *args):
    print(a, args)
    print(type(args))
    
asterisk_test(1, 2, 3, 4, 5, 6)

1 (2, 3, 4, 5, 6)

<class 'tuple'>

 

 

Ex 2) 키워드 인자 사용 예

  • a = 1, **kargs = {'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
  • 키워드 인자는 Dict 형태
def asterisk_test(a, **kargs):
    print(a, kargs)
    print(type(kargs))
    
asterisk_test(1, b=2, c=3, d=4, e=5, f=6)

1 {'b':2, 'c':3, 'd':4, 'e':5, 'f':6}

<class 'dict'>

 

 

Ex 3) unpacking 예 

  • 함수 선언의 args는 하나의 tuple을 받음
  • 이것을 *args를 하여 unpacking 
def asterisk_test(a, args):
    print(a, *args)
    print(type(args))
    
asterisk_test(1, (2,3,4,5,6))

1 2 3 4 5 6     (unpacking 된 결과)

<class 'tuple'>

 

 

Ex 3-1) unpacking 예 2

a, b, c = ([1, 2], [3, 4], [5, 6])
print(a, b, c)

data = ([1, 2], [3, 4], [5, 6])
print(*data)

[1, 2], [3, 4], [5, 6]

[1, 2], [3, 4], [5, 6]

 

 

Ex 3-2) unpacking 예 3

def asterisk_test(a, b, c, d, e):
    print(a, b, c, d, e)
    
data = {"d":1, "c":2, "b":3, "e":56}
asterisk_test(10, **data)

10 3 2 1 56

 

 

Ex 3-3) unpacking 예 4

for data in zip(*([1, 2], [3, 4], [5, 6])):
    print(sum(data))

9    (1 + 3+ 5)

12    (2+ 4 + 6)

 

'✍🏻Language & FrameWork > Python' 카테고리의 다른 글

[Python for ML] News Categorization  (0) 2024.01.02
[Python for ML] Linear Algebra Codes - 1  (2) 2024.01.02
[Python for ML] Reduce 함수  (0) 2024.01.01
[Python for ML] Map 함수  (0) 2024.01.01
[Python for ML] Lambda 함수  (0) 2024.01.01

Reduce 함수

  • map 함수와 달리 list에 똑같은 함수를 적용해서 통합(이전의 계산 결과를 하나의 입력으로 넣는다)
  • 사용을 위해 from functools import reduce 호출
  • Legacy library나 다양한 머신러닝 코드에서 여전히 사용중

 

 

Ex 1) 기본적인 사용 예

from functools import reduce

print(reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]))

15 -> (처음 계산 1 + 2 = 3을 x에 넣고, 다음의 계산 3 + 3 = 6 을 x에 넣고. . . 반복)



Ex 2) 팩토리얼 계산

def factorial(n):
    return reduce(
            lambda x, y: x * y, range(1, n+1))
            
print(factorial(5))

120 -> (1 * 2 * 3 * 4* 5)

 

 

'✍🏻Language & FrameWork > Python' 카테고리의 다른 글

[Python for ML] Linear Algebra Codes - 1  (2) 2024.01.02
[Python for ML] Asterisk  (0) 2024.01.02
[Python for ML] Map 함수  (0) 2024.01.01
[Python for ML] Lambda 함수  (0) 2024.01.01
[Python for ML] Zip 함수  (0) 2024.01.01