Chapter 02
Machine Learning Zoomcamp
NotebookPython 3 (ipykernel)33 cells
Machine Learning Zoomcamp
1.8 Linear algebra refresher
Plan:
- Vector operations
- Multiplication
- Vector-vector multiplication
- Matrix-vector multiplication
- Matrix-matrix multiplication
- Identity matrix
- Inverse
In [1]python · cell 3
python
import numpy as npVector operations
In [2]python · cell 5
python
u = np.array([2, 4, 5, 6])In [6]python · cell 6
python
2 * uOutput
array([ 4, 8, 10, 12])
In [4]python · cell 7
python
v = np.array([1, 0, 0, 2])In [5]python · cell 8
python
u + vOutput
array([3, 4, 5, 8])
In [7]python · cell 9
python
u * vOutput
array([ 2, 0, 0, 12])
Multiplication
In [10]python · cell 11
python
v.shape[0]Output
4
In [11]python · cell 12
python
def vector_vector_multiplication(u, v):
assert u.shape[0] == v.shape[0]
n = u.shape[0]
result = 0.0
for i in range(n):
result = result + u[i] * v[i]
return resultIn [12]python · cell 13
python
vector_vector_multiplication(u, v)Output
14.0
In [13]python · cell 14
python
u.dot(v)Output
14
In [14]python · cell 15
python
U = np.array([
[2, 4, 5, 6],
[1, 2, 1, 2],
[3, 1, 2, 1],
])In [16]python · cell 16
python
U.shapeOutput
(3, 4)
In [17]python · cell 17
python
def matrix_vector_multiplication(U, v):
assert U.shape[1] == v.shape[0]
num_rows = U.shape[0]
result = np.zeros(num_rows)
for i in range(num_rows):
result[i] = vector_vector_multiplication(U[i], v)
return resultIn [18]python · cell 18
python
matrix_vector_multiplication(U, v)Output
array([14., 5., 5.])
In [19]python · cell 19
python
U.dot(v)Output
array([14, 5, 5])
In [20]python · cell 20
python
V = np.array([
[1, 1, 2],
[0, 0.5, 1],
[0, 2, 1],
[2, 1, 0],
])In [21]python · cell 21
python
def matrix_matrix_multiplication(U, V):
assert U.shape[1] == V.shape[0]
num_rows = U.shape[0]
num_cols = V.shape[1]
result = np.zeros((num_rows, num_cols))
for i in range(num_cols):
vi = V[:, i]
Uvi = matrix_vector_multiplication(U, vi)
result[:, i] = Uvi
return resultIn [22]python · cell 22
python
matrix_matrix_multiplication(U, V)Output
array([[14. , 20. , 13. ],
[ 5. , 6. , 5. ],
[ 5. , 8.5, 9. ]])In [23]python · cell 23
python
U.dot(V)Output
array([[14. , 20. , 13. ],
[ 5. , 6. , 5. ],
[ 5. , 8.5, 9. ]])Identity matrix
In [25]python · cell 25
python
I = np.eye(3)In [28]python · cell 26
python
VOutput
array([[1. , 1. , 2. ],
[0. , 0.5, 1. ],
[0. , 2. , 1. ],
[2. , 1. , 0. ]])In [27]python · cell 27
python
V.dot(I)Output
array([[1. , 1. , 2. ],
[0. , 0.5, 1. ],
[0. , 2. , 1. ],
[2. , 1. , 0. ]])Inverse
In [31]python · cell 29
python
Vs = V[[0, 1, 2]]
VsOutput
array([[1. , 1. , 2. ],
[0. , 0.5, 1. ],
[0. , 2. , 1. ]])In [33]python · cell 30
python
Vs_inv = np.linalg.inv(Vs)
Vs_invOutput
array([[ 1. , -2. , 0. ],
[ 0. , -0.66666667, 0.66666667],
[ 0. , 1.33333333, -0.33333333]])In [34]python · cell 31
python
Vs_inv.dot(Vs)Output
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])Next
Intro to Pandas
In [ ]python · cell 33
python
