1. 程式人生 > >斯坦福cs231n計算機視覺課訓練營之矩陣類

斯坦福cs231n計算機視覺課訓練營之矩陣類

根據python和numpy的教程,寫一個矩陣的類。

Matrix.pyMatrix.py

class Matrix:
    def __init__(self, lst2d):
        self._values = [row[:] for row in lst2d]

    def __repr__(self):
        return "Matrix({})".format(self._values)

    __str__ = __repr__
	
    # 獲取矩陣的形狀
    def shape(self):
        return len
(self._values), len(self._values[0]) # 獲取矩陣的行數 def row_num(self): return self.shape()[0] __len__ = row_num # 獲取矩陣的列數 def col_num(self): return self.shape()[1] # 獲取矩陣的大小 def size(self): r, c = self.shape() return r * c # 獲取矩陣的元素 def __getitem__
(self, item): r, c = item return self._values[r][c] # 獲取矩陣指定行 def row_vector(self, index): return list(self._values[index]) # 獲取矩陣指定列 def col_vector(self, index): return list([row[index] for row in self._values]) # 獲取矩陣加法 def __add__(self,
other): assert self.shape() == other.shape(), \ "Error in adding. Shape of matrix must be same." return Matrix([[a + b for a, b in zip(self.row_vector(i), other.row_vector(i))] for i in range(self.row_num())]) # 獲取矩陣減法 def __sub__(self, other): assert self.shape() == other.shape(), \ "Error in subtracting. Shape of matrix must be same." return Matrix([[a - b for a, b in zip(self.row_vector(i), other.row_vector(i))] for i in range(self.row_num())]) # 獲取矩陣乘法 def __mul__(self, k): return Matrix([[e * k for e in self.row_vector(i)] for i in range(self.row_num())]) # 獲取矩陣右乘 def __rmul__(self, k): return self * k # 獲取矩陣除法 def __truediv__(self, other): return (1 / other) * self # 矩陣取正 def __pos__(self): return 1 * self # 矩陣取負 def __neg__(self): return -1 * self # 構造零矩陣 @classmethod def zero(cls, r, c): return cls([[0] * c for _ in range(r)]) # 獲取矩陣點乘 def dot(self, other): if isinstance(other, Vector): # 矩陣和向量的乘法 assert self.col_num() == len(other), \ "Error in Matrix-Vector Multiplication." return Vector([self.row_vector(i).dot(other) for i in range(self.row_num())]) if isinstance(other, Matrix): # 矩陣和矩陣的乘法 assert self.col_num() == other.row_num(), \ "Error in Matrix-Matrix Multiplication." return Matrix([[self.row_vector(i).dot(other.col_vector(j)) for j in range(other.col_num())] for i in range(self.row_num())]) # 獲取矩陣轉置 def T(self): return Matrix([[e for e in self.col_vector(i)] for i in range(self.col_num())])

main.pymain.py

from playLA.Matrix import Matrix

if __name__ == '__main__':
    matrix = Matrix([[1, 2], [3, 4]])

    print(matrix)

    print(matrix.shape())
    print(len(matrix))

    print(matrix[0, 0])

    print(matrix.col_vector(1))

    matrix2 = Matrix([[5, 6], [7, 8]])

    print(matrix + matrix2)
    print(matrix - matrix2)

    print(matrix * 2)
    print(2 * matrix)

    print(Matrix.zero(3, 2))

    matrix3 = Matrix([[1.5, 0], [0, 2]])
    matrix4 = list([5, 3])

    print("A:{}, B:{} \nA.dot(B)={}".format(matrix3, matrix4, matrix3.dot(matrix4)))
    print("A:{}, B:{} \nA.dot(B)={}".format(matrix, matrix2, matrix.dot(matrix2)))

    matrix5 = Matrix([[1, 2, 3], [4, 5, 6]])
    print("matrix5.T = {}".format(matrix5.T()))

##### output ###
Matrix([[1, 2], [3, 4]])
(2, 2)
2
1
(2, 4)
Matrix([[6, 8], [10, 12]])
Matrix([[-4, -4], [-4, -4]])
Matrix([[2, 4], [6, 8]])
Matrix([[2, 4], [6, 8]])
Matrix([[0, 0], [0, 0], [0, 0]])
A:Matrix([[1.5, 0], [0, 2]]), B:(5, 3) 
A.dot(B)=(7.5, 6)
A:Matrix([[1, 2], [3, 4]]), B:Matrix([[5, 6], [7, 8]]) 
A.dot(B)=Matrix([[19, 22], [43, 50]])
matrix5.T = Matrix([[1, 4], [2, 5], [3, 6]])