MLearning
/
Numpy
- 1 Supervised ML 4
-
Classifier S
-
Linear model S
-
Basis expansion S
-
Regularization S
- 2 Matplotlib 2
-
Subplots S
-
Pyplot S
- 3 Datasets 4
-
Iris species S
-
Diabetes S
-
Breast cancer S
-
Simulated data S
- 4 Numpy 7
-
Matrices S
-
Sparse matrices S
-
Vectorize S
-
Average S
-
Standard deviation S
-
Reshape S
-
Multiplication S
- 5 Pandas 5
-
Read data S
-
Data cleaning S
-
Find values S
-
Group rows S
-
Merge data S
- 6 Calculus 2
-
Derivatives S
-
Integrals S
- 7 Algorithms 3
-
K nearest neighbors S
-
Linear regression S
-
Gradient descent S
S
R
Q
ML Numpy Reshape
New matrix should have the same size as original The argument -1 means "as many as needed" A = matrix.reshape(2, 6) B = matrix.reshape(1, -1)
Reshape
p09 The new matrix should have the same size as original matrix.
""" Matrix Reshape
Reshape maintain the data but as different numbers of rows and columns.
The new matrix should have the same size as original matrix
The argument -1 means "as many as needed"
Flatten transform a matrix into a one-dimensional array.
"""
import numpy as np
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
])
A = matrix.reshape(2, 6)
B = matrix.reshape(1, -1)
C = matrix.flatten()
print(A) # [[ 1 2 3 4 5 6] [ 7 8 9 10 11 12]]
print(B) # [[ 1 2 3 4 5 6 7 8 9 10 11 12]]
print(C) # [ 1 2 3 4 5 6 7 8 9 10 11 12]
assert matrix.size == A.size # passed
assert matrix.size == B.size # passed
assert matrix.size == C.size # passed
➥ Transpose (T)
Transpose (T)
p11 The column and row indeces of each element are swapped.
""" Transpose Matrix
Transposing is a common operation in linear algebra
Indices of column and rows of each element are swapped
A vector cannot be transposed
"""
import numpy as np
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
mT = matrix.T
print(mT)
# [1 4 7]
# [2 5 8]
# [3 6 9]
assert matrix[0, 1] == mT[1, 0] # passed
assert matrix[1, 0] == mT[0, 1] # passed
assert matrix[1, 1] == mT[1, 1] # passed
➥ Inverse (I)
Inverse (I)
p18 Calculate the inverse of a square matrix.
""" Inverse Matrix
Calculate the inverse of a square matrix.
The new matrix A_inv is calculated so that
A * A_inv = I
"""
import numpy as np
A = np.array([
[4, 3],
[3, 2],
])
I = np.array([
[1, 0],
[0, 1],
])
AInv = np.linalg.inv(A)
print(AInv)
# [-2 3]
# [ 3 -4]
print(A @ AInv)
# [1 0]
# [0 1]
assert (A @ AInv == I) .all() # passed
assert (AInv @ A == I) .all() # passed
➥ Questions
Last update: 47 days ago