线性代数 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)))

4.4 实现矩阵的基本计算

Matrix.py

    def __add__(self, another):
        assert self.shape() == another.shape(),"ERROR in shape"
        return Matrix([[a + b for a, b in zip(self.row_vector(i), another.row_vector(i))]for i in range(self.row_num())])
    def __sub__(self, another):
        assert self.shape() == another.shape(),"ERROR in shape"
        return Matrix([[a - b for a, b in zip(self.row_vector(i), another.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, k):
        return (1/k) * 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)])

main_matrix.py

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

4.8实现矩阵乘法

Matrix.py

main_matrix.py

Matrix.py

    def dot(self, another):
        if isinstance(another, Vector):
            assert self.col_num() == len(another), "error in shape"
            return Vector([self.row_vector(i).dot(another) for i in range(self.row_num())])
        if isinstance(another, Matrix):
            assert self.col_num() == another.row_num(),"error in shape"
            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

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

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

main_numpy_matrix.py

import numpy as np

if __name__ == "__main__":
    #创建矩阵
    A = np.array([[1, 2], [3, 4]])
    print(A)
    #矩阵属性
    print(A.shape)
    print(A.T)
    #获取矩阵元素
    print(A[1, 1])
    print(A[0])
    print(A[:, 0])
    print(A[1, :])
    #矩阵的基本运算
    B = np.array([[5, 6], [7, 8]])
    print(A + B)
    print(A - B)
    print(10 * A)
    print(A * 10)
    print(A * B)
    print(A.dot(B))


 
 

5 矩阵进阶

5.3 矩阵变换

main_matrix_transformation.py

import math

import matplotlib.pyplot as plt
from playLA.Matrix import Matrix
from playLA.Vector import Vector
if __name__ == "__main__":
    points = [[0, 0], [0, 5], [3, 5], [3, 4], [1, 4],
              [1, 3], [2, 3], [2, 2], [1, 2], [1, 0]]
    x = [point[0] for point in points]
    y = [point[1] for point in points]
    plt.figure(figsize=(5, 5))
    plt.xlim(-10, 10)
    plt.ylim(-10, 10)
    plt.plot(x, y)
    # plt.show()
    P = Matrix(points)
    # T = Matrix([[2, 0], [0, 1.5]])#x扩大2倍,y扩大1.5倍
    # T = Matrix([[1, 0], [0, -1]])#关于X轴对称
    # T = Matrix([[-1, 0], [0, 1]])#关于X轴对称
    # T = Matrix([[-1, 0], [0, -1]])#关于原点对称
    # T = Matrix([[1, 0.5], [0, 1]])
    # T = Matrix([[1, 0], [0.5, 1]])
    theta = math.pi / 3
    #旋转theta角度
    T = Matrix([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]])
    P2 = T.dot(P.T())
    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())])
    plt.show()

 

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

 

 

Matrix.py

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

main_matrix.py

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

 main_numpy_matrix.py

    #numpy中的逆矩阵
    invA = np.linalg.inv(A)
    print(invA)
    print(A.dot(invA))
    print(invA.dot(A))

    C = np.array([[1,2]])
    print(np.linalg.inv(C))

5.8用矩阵表示空间

 

 

 

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

 

6 线性系统

6.4实现高斯-约旦消元法

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Basics of Linear Algebra for Machine Learning: Discover the Mathematical Language of Data in Python By 作者: Jason Brownlee Pub Date: 2018 ISBN: n/a Pages: 212 Language: English Format: PDF Linear algebra is a pillar of machine learning. You cannot develop a deep understanding and application of machine learning without it. In this new laser-focused Ebook written in the friendly Machine Learning Mastery style that you’re used to, you will finally cut through the equations, Greek letters, and confusion, and discover the topics in linear algebra that you need to know. Using clear explanations, standard Python libraries, and step-by-step tutorial lessons, you will discover what linear algebra is, the importance of linear algebra to machine learning, vector, and matrix operations, matrix factorization, principal component analysis, and much more. This book was designed to be a crash course in linear algebra for machine learning practitioners. Ideally, those with a background as a developer. This book was designed around major data structures, operations, and techniques in linear algebra that are directly relevant to machine learning algorithms. There are a lot of things you could learn about linear algebra, from theory to abstract concepts to APIs. My goal is to take you straight to developing an intuition for the elements you must understand with laser-focused tutorials. I designed the tutorials to focus on how to get things done with linear algebra. They give you the tools to both rapidly understand and apply each technique or operation. Each tutorial is designed to take you about one hour to read through and complete, excluding the extensions and further reading. You can choose to work through the lessons one per day, one per week, or at your own pace. I think momentum is critically important, and this book is intended to be read and used, not to sit idle. I would recommend picking a schedule and sticking to it. The tutorials are divided into five parts: Foundation. Discover a gentle introduction to the field of linear algebra and the relationship it has with the field of machine learning. NumPy. Discover NumPy tutorials that show you how to create, index, slice, and reshape NumPy arrays, the main data structure used in machine learning and the basis for linear algebra examples in this book. Matrices. Discover the key structures for holding and manipulating data in linear algebra in vectors, matrices, and tensors. Factorization. Discover a suite of methods for decomposing a matrix into its constituent elements in order to make numerical operations more efficient and more stable. Statistics. Discover statistics through the lens of linear algebra and its application to principal component analysis and linear regression.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值