線性代數 linear algebra

2.3 實現屬於我們自己的向量

Vector.py

class Vector:
    def __init__(self, lst):
        self._values = lst
    #return len
    def __len__(self):
        return len(self._values)
    #return index th item
    def __getitem__(self, index):
        return self._values[index]
    #direct use call this method
    def __repr__(self):
        return "Vector({})".format(self._values)
    #print call this method
    def __str__(self):
        return "({})".format(", ".join(str(e) for e in self._values))


main_vector.py

import sys
import numpy
import scipy
from playLA.Vector import  Vector

if __name__ == "__main__":
    vec = Vector([5, 2])
    print(vec)
    print(len(vec))
    print("vec[0] = {}, vec[1] = {}".format(vec[0], vec[1]))

2.5 實現向量的基本運算

Vector.py

class Vector:
    def __init__(self, lst):
        self._values = lst
    #return len
    def __len__(self):
        return len(self._values)
    #return index th item
    def __getitem__(self, index):
        return self._values[index]
    #direct use call this method
    def __repr__(self):
        return "Vector({})".format(self._values)
    #print call this method
    def __str__(self):
        return "({})".format(", ".join(str(e) for e in self._values))
    #vector add method
    def __add__(self, another):
        assert  len(self) == len(another),"lenth not same"
        # return Vector([a + b for a, b in zip(self._values, another._values)])
        return Vector([a + b for a, b in zip(self, another)])
    #迭代器 設計_values其實是私有成員變量,不想別人訪問,所以使用迭代器
    #單雙下劃線開頭體現在繼承上,如果類內內部使用的變量使用單下劃線
    def __iter__(self):
        return self._values.__iter__()
    #sub
    def __sub__(self, another):
        # return Vector([a + b for a, b in zip(self._values, another._values)])
        return Vector([a - b for a, b in zip(self, another)])
    #self * k
    def __mul__(self, k):
        return Vector([k * e for e in self])
    # k * self
    def __rmul__(self, k):
        return Vector([k * e for e in self])
    #取正
    def __pos__(self):
        return 1 * self
    #取反
    def __neg__(self):
        return -1 * self

main_vector.py

import sys
import numpy
import scipy
from playLA.Vector import  Vector

if __name__ == "__main__":
    vec = Vector([5, 2])
    print(vec)
    print(len(vec))
    print("vec[0] = {}, vec[1] = {}".format(vec[0], vec[1]))
    vec2 = Vector([3, 1])
    print("{} + {} = {}".format(vec, vec2, vec + vec2))
    print("{} - {} = {}".format(vec, vec2, vec - vec2))
    print("{} * {} = {}".format(vec, 3, vec * 3))
    print("{} * {} = {}".format(3, vec, vec * 3))
    print("-{} = {}".format(vec, -vec))
    print("+{} = {}".format(vec, +vec))

2.8 實現0向量

Vector.py

    @classmethod
    def zero(cls, dim):
        return cls([0] * dim)

main_vector.py

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

3.2實現向量規範

Vector.py

    # self / k
    def __truediv__(self, k):
        return Vector((1 / k) * self)
    #模
    def norm(self):
        return math.sqrt(sum(e**2 for e in self))
    #歸一化
    def normalize(self):
        if self.norm() < EPSILON:
            raise ZeroDivisionError("Normalize error! norm is zero.")
        return Vector(self._values)/self.norm()

main_vector.py

    print("normalize vec is ({})".format(vec.normalize()))
    print(vec.normalize().norm())
    try :
        zero2.normalize()
    except ZeroDivisionError:
        print("cant normalize zero vector {}".format(zero2))

3.3 向量的點乘

3.5實現向量的點乘操作

Vector.py

    def dot(self, another):
        assert len(self) == len(another), "Error in dot product. Length of vectors must be same."
        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

import numpy as np
if __name__ == "__main__":
    print(np.__version__)

    lst = [1, 2, 3]
    lst[0] = "LA"
    print(lst)
    #numpy中只能存儲一種數據
    vec = np.array([1, 2, 3])
    print(vec)
    # vec[0] = "LA"
    # vec[0] = 666
    print(vec)
    print(np.zeros(5))
    print(np.ones(5))
    print(np.full(5, 666))

    print(vec)
    print("size = ", vec.size)
    print("size = ", len(vec))
    print(vec[0])
    print(vec[-1])
    print(vec[0:2])
    print(type(vec[0:2]))
    #點乘
    vec2 = np.array([4, 5, 6])
    print("{} + {} = {}".format(vec, vec2, vec + vec2))
    print("{} - {} = {}".format(vec, vec2, vec - vec2))
    print("{} * {} = {}".format(2, vec, 2 * vec))
    print("{} * {} = {}".format(vec, 2, vec * 2))
    print("{} * {} = {}".format(vec, vec2, vec * vec2))
    print("{}.dot({})= {}".format(vec, vec2, vec.dot(vec2)))
    #求模
    print(np.linalg.norm(vec))
    print(vec/ np.linalg.norm(vec))
    print(np.linalg.norm(vec/ np.linalg.norm(vec)))
    #爲什麼輸出nan
    zero3 = np.zeros(3)
    print(zero3 /np.linalg.norm(zero3))

4矩陣

4.2實現矩陣

Matrix.py

from .Vector import Vector
class Matrix:
    #list2d二維數組
    def __init__(self, list2d):
        self._values = [row[:] for row in list2d]
    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]
    def col_num(self):
        return self.shape()[1]
    def size(self):
        r, c = self.shape()
        return r * c
    __len__ = row_num
    def __getitem__(self, pos):
        r, c =pos
        return self._values[r][c]
    #第index個行向量
    def row_vector(self, index):
        return Vector(self._values[index])
    def col_vector(self, index):
        return Vector([row[index] for row in self._values])

main_matrix.py

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

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章