线性代数 linear algebra

2.3 实现属于我们自己的向量

Vector.py

  1.  
    class Vector:
  2.  
    def __init__(self, lst):
  3.  
    self._values = lst
  4.  
    #return len
  5.  
    def __len__(self):
  6.  
    return len(self._values)
  7.  
    #return index th item
  8.  
    def __getitem__(self, index):
  9.  
    return self._values[index]
  10.  
    #direct use call this method
  11.  
    def __repr__(self):
  12.  
    return "Vector({})".format(self._values)
  13.  
    #print call this method
  14.  
    def __str__(self):
  15.  
    return "({})".format(", ".join(str(e) for e in self._values))
  16.  
     
  17.  
     

main_vector.py

  1.  
    import sys
  2.  
    import numpy
  3.  
    import scipy
  4.  
    from playLA.Vector import Vector
  5.  
     
  6.  
    if __name__ == "__main__":
  7.  
    vec = Vector([5, 2])
  8.  
    print(vec)
  9.  
    print(len(vec))
  10.  
    print("vec[0] = {}, vec[1] = {}".format(vec[0], vec[1]))

2.5 实现向量的基本运算

Vector.py

  1.  
    class Vector:
  2.  
    def __init__(self, lst):
  3.  
    self._values = lst
  4.  
    #return len
  5.  
    def __len__(self):
  6.  
    return len(self._values)
  7.  
    #return index th item
  8.  
    def __getitem__(self, index):
  9.  
    return self._values[index]
  10.  
    #direct use call this method
  11.  
    def __repr__(self):
  12.  
    return "Vector({})".format(self._values)
  13.  
    #print call this method
  14.  
    def __str__(self):
  15.  
    return "({})".format(", ".join(str(e) for e in self._values))
  16.  
    #vector add method
  17.  
    def __add__(self, another):
  18.  
    assert len(self) == len(another),"lenth not same"
  19.  
    # return Vector([a + b for a, b in zip(self._values, another._values)])
  20.  
    return Vector([a + b for a, b in zip(self, another)])
  21.  
    #迭代器 设计_values其实是私有成员变量,不想别人访问,所以使用迭代器
  22.  
    #单双下划线开头体现在继承上,如果类内内部使用的变量使用单下划线
  23.  
    def __iter__(self):
  24.  
    return self._values.__iter__()
  25.  
    #sub
  26.  
    def __sub__(self, another):
  27.  
    # return Vector([a + b for a, b in zip(self._values, another._values)])
  28.  
    return Vector([a - b for a, b in zip(self, another)])
  29.  
    #self * k
  30.  
    def __mul__(self, k):
  31.  
    return Vector([k * e for e in self])
  32.  
    # k * self
  33.  
    def __rmul__(self, k):
  34.  
    return Vector([k * e for e in self])
  35.  
    #取正
  36.  
    def __pos__(self):
  37.  
    return 1 * self
  38.  
    #取反
  39.  
    def __neg__(self):
  40.  
    return -1 * self

main_vector.py

  1.  
    import sys
  2.  
    import numpy
  3.  
    import scipy
  4.  
    from playLA.Vector import Vector
  5.  
     
  6.  
    if __name__ == "__main__":
  7.  
    vec = Vector([5, 2])
  8.  
    print(vec)
  9.  
    print(len(vec))
  10.  
    print("vec[0] = {}, vec[1] = {}".format(vec[0], vec[1]))
  11.  
    vec2 = Vector([3, 1])
  12.  
    print("{} + {} = {}".format(vec, vec2, vec + vec2))
  13.  
    print("{} - {} = {}".format(vec, vec2, vec - vec2))
  14.  
    print("{} * {} = {}".format(vec, 3, vec * 3))
  15.  
    print("{} * {} = {}".format(3, vec, vec * 3))
  16.  
    print("-{} = {}".format(vec, -vec))
  17.  
    print("+{} = {}".format(vec, +vec))

2.8 实现0向量

Vector.py

  1.  
    @classmethod
  2.  
    def zero(cls, dim):
  3.  
    return cls([0] * dim)

main_vector.py

  1.  
    zero2 = Vector.zero(2)
  2.  
    print(zero2)
  3.  
    print("{} + {} = {}".format(vec, zero2, vec + zero2))

3.2实现向量规范

Vector.py

  1.  
    # self / k
  2.  
    def __truediv__(self, k):
  3.  
    return Vector((1 / k) * self)
  4.  
    #模
  5.  
    def norm(self):
  6.  
    return math.sqrt(sum(e**2 for e in self))
  7.  
    #归一化
  8.  
    def normalize(self):
  9.  
    if self.norm() < EPSILON:
  10.  
    raise ZeroDivisionError("Normalize error! norm is zero.")
  11.  
    return Vector(self._values)/self.norm()

main_vector.py

  1.  
    print("normalize vec is ({})".format(vec.normalize()))
  2.  
    print(vec.normalize().norm())
  3.  
    try :
  4.  
    zero2.normalize()
  5.  
    except ZeroDivisionError:
  6.  
    print("cant normalize zero vector {}".format(zero2))

3.3 向量的点乘

3.5实现向量的点乘操作

Vector.py

  1.  
    def dot(self, another):
  2.  
    assert len(self) == len(another), "Error in dot product. Length of vectors must be same."
  3.  
    return sum(a * b for a, b in zip(self, another))

 main_vector.py

    print(vec.dot(vec2))

3.6向量点乘的应用

3.7numpy中向量的基本使用

main_numpy_vector.py

  1.  
    import numpy as np
  2.  
    if __name__ == "__main__":
  3.  
    print(np.__version__)
  4.  
     
  5.  
    lst = [1, 2, 3]
  6.  
    lst[0] = "LA"
  7.  
    print(lst)
  8.  
    #numpy中只能存储一种数据
  9.  
    vec = np.array([1, 2, 3])
  10.  
    print(vec)
  11.  
    # vec[0] = "LA"
  12.  
    # vec[0] = 666
  13.  
    print(vec)
  14.  
    print(np.zeros(5))
  15.  
    print(np.ones(5))
  16.  
    print(np.full(5, 666))
  17.  
     
  18.  
    print(vec)
  19.  
    print("size = ", vec.size)
  20.  
    print("size = ", len(vec))
  21.  
    print(vec[0])
  22.  
    print(vec[-1])
  23.  
    print(vec[0:2])
  24.  
    print(type(vec[0:2]))
  25.  
    #点乘
  26.  
    vec2 = np.array([4, 5, 6])
  27.  
    print("{} + {} = {}".format(vec, vec2, vec + vec2))
  28.  
    print("{} - {} = {}".format(vec, vec2, vec - vec2))
  29.  
    print("{} * {} = {}".format(2, vec, 2 * vec))
  30.  
    print("{} * {} = {}".format(vec, 2, vec * 2))
  31.  
    print("{} * {} = {}".format(vec, vec2, vec * vec2))
  32.  
    print("{}.dot({})= {}".format(vec, vec2, vec.dot(vec2)))
  33.  
    #求模
  34.  
    print(np.linalg.norm(vec))
  35.  
    print(vec/ np.linalg.norm(vec))
  36.  
    print(np.linalg.norm(vec/ np.linalg.norm(vec)))
  37.  
    #为什么输出nan
  38.  
    zero3 = np.zeros(3)
  39.  
    print(zero3 /np.linalg.norm(zero3))

4矩阵

4.2实现矩阵

Matrix.py

  1.  
    from .Vector import Vector
  2.  
    class Matrix:
  3.  
    #list2d二维数组
  4.  
    def __init__(self, list2d):
  5.  
    self._values = [row[:] for row in list2d]
  6.  
    def __repr__(self):
  7.  
    return "Matrix({})".format(self._values)
  8.  
    __str__ = __repr__
  9.  
    def shape(self):
  10.  
    return len(self._values),len(self._values[0])
  11.  
    def row_num(self):
  12.  
    return self.shape()[0]
  13.  
    def col_num(self):
  14.  
    return self.shape()[1]
  15.  
    def size(self):
  16.  
    r, c = self.shape()
  17.  
    return r * c
  18.  
    __len__ = row_num
  19.  
    def __getitem__(self, pos):
  20.  
    r, c =pos
  21.  
    return self._values[r][c]
  22.  
    #第index个行向量
  23.  
    def row_vector(self, index):
  24.  
    return Vector(self._values[index])
  25.  
    def col_vector(self, index):
  26.  
    return Vector([row[index] for row in self._values])

main_matrix.py

  1.  
    from playLA.Matrix import Matrix
  2.  
    if __name__ == "__main__":
  3.  
    matrix = Matrix([[1, 2],[3, 4]])
  4.  
    print(matrix)
  5.  
    print("matrix.shape = {}".format(matrix.shape()))
  6.  
    print("matrix.size = {}".format(matrix.size()))
  7.  
    print("matrix.len = {}".format(len(matrix)))
  8.  
    print("matrix[0][0]= {}".format(matrix[0, 0]))
  9.  
    print("{}".format(matrix.row_vector(0)))
  10.  
    print("{}".format(matrix.col_vector(0)))

4.4 实现矩阵的基本计算

Matrix.py

  1.  
    def __add__(self, another):
  2.  
    assert self.shape() == another.shape(),"ERROR in shape"
  3.  
    return Matrix([[a + b for a, b in zip(self.row_vector(i), another.row_vector(i))]for i in range(self.row_num())])
  4.  
    def __sub__(self, another):
  5.  
    assert self.shape() == another.shape(),"ERROR in shape"
  6.  
    return Matrix([[a - b for a, b in zip(self.row_vector(i), another.row_vector(i))]for i in range(self.row_num())])
  7.  
    def __mul__(self, k):
  8.  
    return Matrix([[e*k for e in self.row_vector(i)] for i in range(self.row_num())])
  9.  
    def __rmul__(self, k):
  10.  
    return self * k
  11.  
    #数量除法
  12.  
    def __truediv__(self, k):
  13.  
    return (1/k) * self
  14.  
    def __pos__(self):
  15.  
    return 1 * self
  16.  
    def __neg__(self):
  17.  
    return -1 * self
  18.  
    @classmethod
  19.  
    def zero(cls, r, c):
  20.  
    return cls([[0]*c for _ in range(r)])

main_matrix.py

  1.  
    matrix2 = Matrix([[5, 6], [7, 8]])
  2.  
    print("add: {}".format(matrix + matrix2))
  3.  
    print("sub: {}".format(matrix - matrix2))
  4.  
    print("mul: {}".format(matrix * 2))
  5.  
    print("rmul: {}".format(2 * matrix))
  6.  
    print("zero_2_3:{}".format(Matrix.zero(2, 3)))

4.8实现矩阵乘法

Matrix.py

main_matrix.py

Matrix.py

  1.  
    def dot(self, another):
  2.  
    if isinstance(another, Vector):
  3.  
    assert self.col_num() == len(another), "error in shape"
  4.  
    return Vector([self.row_vector(i).dot(another) for i in range(self.row_num())])
  5.  
    if isinstance(another, Matrix):
  6.  
    assert self.col_num() == another.row_num(),"error in shape"
  7.  
    return Matrix([self.row_vector(i).dot(another.col_vector(j)) for j in range(another.col_num())] for i in range(self.row_num()))

main_matrix.py

  1.  
    T = Matrix([[1.5, 0], [0, 2]])
  2.  
    p = Vector([5, 3])
  3.  
    print("T.dot(p)= {}".format(T.dot(p)))
  4.  
    P = Matrix([[0, 4, 5], [0, 0, 3]])
  5.  
    print("T.dot(P)={}".format(T.dot(P)))

4.11 实现矩阵转置和Numpy中的矩阵

main_numpy_matrix.py

  1.  
    import numpy as np
  2.  
     
  3.  
    if __name__ == "__main__":
  4.  
    #创建矩阵
  5.  
    A = np.array([[1, 2], [3, 4]])
  6.  
    print(A)
  7.  
    #矩阵属性
  8.  
    print(A.shape)
  9.  
    print(A.T)
  10.  
    #获取矩阵元素
  11.  
    print(A[1, 1])
  12.  
    print(A[0])
  13.  
    print(A[:, 0])
  14.  
    print(A[1, :])
  15.  
    #矩阵的基本运算
  16.  
    B = np.array([[5, 6], [7, 8]])
  17.  
    print(A + B)
  18.  
    print(A - B)
  19.  
    print(10 * A)
  20.  
    print(A * 10)
  21.  
    print(A * B)
  22.  
    print(A.dot(B))
  23.  
     
  24.  
     

 
 

5 矩阵进阶

5.3 矩阵变换

main_matrix_transformation.py

  1.  
    import math
  2.  
     
  3.  
    import matplotlib.pyplot as plt
  4.  
    from playLA.Matrix import Matrix
  5.  
    from playLA.Vector import Vector
  6.  
    if __name__ == "__main__":
  7.  
    points = [[0, 0], [0, 5], [3, 5], [3, 4], [1, 4],
  8.  
    [1, 3], [2, 3], [2, 2], [1, 2], [1, 0]]
  9.  
    x = [point[0] for point in points]
  10.  
    y = [point[1] for point in points]
  11.  
    plt.figure(figsize=(5, 5))
  12.  
    plt.xlim(-10, 10)
  13.  
    plt.ylim(-10, 10)
  14.  
    plt.plot(x, y)
  15.  
    # plt.show()
  16.  
    P = Matrix(points)
  17.  
    # T = Matrix([[2, 0], [0, 1.5]])#x扩大2倍,y扩大1.5倍
  18.  
    # T = Matrix([[1, 0], [0, -1]])#关于X轴对称
  19.  
    # T = Matrix([[-1, 0], [0, 1]])#关于X轴对称
  20.  
    # T = Matrix([[-1, 0], [0, -1]])#关于原点对称
  21.  
    # T = Matrix([[1, 0.5], [0, 1]])
  22.  
    # T = Matrix([[1, 0], [0.5, 1]])
  23.  
    theta = math.pi / 3
  24.  
    #旋转theta角度
  25.  
    T = Matrix([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]])
  26.  
    P2 = T.dot(P.T())
  27.  
    plt.plot([P2.col_vector(i)[0] for i in range(P2.col_num())],[P2.col_vector(i)[1] for i in range(P2.col_num())])
  28.  
    plt.show()

 

5.6实现单位矩阵和numpy中的逆矩阵

 

 

Matrix.py

  1.  
    #单位矩阵
  2.  
    @classmethod
  3.  
    def identity(cls, n):
  4.  
    m = [[0]*n for _ in range(n)]
  5.  
    for i in range(n):
  6.  
    m[i][i] = 1
  7.  
    return cls(m)

main_matrix.py

  1.  
    I = Matrix.identity(2)
  2.  
    print(I)
  3.  
    print("A.dot(I) = {}".format(matrix.dot(I)))
  4.  
    print("I.dot(A) = {}".format(I.dot(matrix)))

 main_numpy_matrix.py

  1.  
    #numpy中的逆矩阵
  2.  
    invA = np.linalg.inv(A)
  3.  
    print(invA)
  4.  
    print(A.dot(invA))
  5.  
    print(invA.dot(A))
  6.  
     
  7.  
    C = np.array([[1,2]])
  8.  
    print(np.linalg.inv(C))

5.8用矩阵表示空间

 

 

 

x轴就是(0,1)y轴就是(-1,0)

 

6 线性系统

6.4实现高斯-约旦消元法

 

https://blog.csdn.net/weixin_40709094/article/details/105602775

posted @ 2020-11-06 08:18  小石小石摩西摩西  阅读(224)  评论(0编辑  收藏  举报