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))

main_vector.py

  1. import sys
  2. import numpy
  3. import scipy
  4. from playLA.Vector import Vector
  5. if __name__ == "__main__":
  6. vec = Vector([ 5, 2])
  7. print(vec)
  8. print(len(vec))
  9. 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. if __name__ == "__main__":
  6. vec = Vector([ 5, 2])
  7. print(vec)
  8. print(len(vec))
  9. print( "vec[0] = {}, vec[1] = {}".format(vec[0], vec[1]))
  10. vec2 = Vector([ 3, 1])
  11. print( "{} + {} = {}".format(vec, vec2, vec + vec2))
  12. print( "{} - {} = {}".format(vec, vec2, vec - vec2))
  13. print( "{} * {} = {}".format(vec, 3, vec * 3))
  14. print( "{} * {} = {}".format(3, vec, vec * 3))
  15. print( "-{} = {}".format(vec, -vec))
  16. 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. lst = [ 1, 2, 3]
  5. lst[ 0] = "LA"
  6. print(lst)
  7. #numpy中只能存储一种数据
  8. vec = np.array([ 1, 2, 3])
  9. print(vec)
  10. # vec[0] = "LA"
  11. # vec[0] = 666
  12. print(vec)
  13. print(np.zeros( 5))
  14. print(np.ones( 5))
  15. print(np.full( 5, 666))
  16. print(vec)
  17. print( "size = ", vec.size)
  18. print( "size = ", len(vec))
  19. print(vec[ 0])
  20. print(vec[ -1])
  21. print(vec[ 0:2])
  22. print(type(vec[ 0:2]))
  23. #点乘
  24. vec2 = np.array([ 4, 5, 6])
  25. print( "{} + {} = {}".format(vec, vec2, vec + vec2))
  26. print( "{} - {} = {}".format(vec, vec2, vec - vec2))
  27. print( "{} * {} = {}".format(2, vec, 2 * vec))
  28. print( "{} * {} = {}".format(vec, 2, vec * 2))
  29. print( "{} * {} = {}".format(vec, vec2, vec * vec2))
  30. print( "{}.dot({})= {}".format(vec, vec2, vec.dot(vec2)))
  31. #求模
  32. print(np.linalg.norm(vec))
  33. print(vec/ np.linalg.norm(vec))
  34. print(np.linalg.norm(vec/ np.linalg.norm(vec)))
  35. #为什么输出nan
  36. zero3 = np.zeros( 3)
  37. 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. if __name__ == "__main__":
  3. #创建矩阵
  4. A = np.array([[ 1, 2], [3, 4]])
  5. print(A)
  6. #矩阵属性
  7. print(A.shape)
  8. print(A.T)
  9. #获取矩阵元素
  10. print(A[ 1, 1])
  11. print(A[ 0])
  12. print(A[:, 0])
  13. print(A[ 1, :])
  14. #矩阵的基本运算
  15. B = np.array([[ 5, 6], [7, 8]])
  16. print(A + B)
  17. print(A - B)
  18. print( 10 * A)
  19. print(A * 10)
  20. print(A * B)
  21. print(A.dot(B))

5 矩阵进阶

5.3 矩阵变换

main_matrix_transformation.py

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

线性代数 linear algebra相关推荐

  1. 【机器学习的数学基础】(二)线性代数(Linear Algebra)(中)

    文章目录 2 线性代数(Linear Algebra)(中) 2.4 向量空间 2.4.1 群 2.4.2 向量空间 2.4.3 向量子空间 2.5 线性独立 2.6 基和秩 2.6.1 生成集和基 ...

  2. MIT 线性代数 Linear Algebra 26:复矩阵,傅里叶矩阵, 快速傅里叶变换 FFT

    这一讲我们来讲一下复矩阵.线性代数中,复矩阵是避免不了的话题,因为一个简单实矩阵都有可能有复数特征值. 复矩阵 我们着重看一下复矩阵和实矩阵在运算上的区别. 距离 首先,一个复数向量的的距离求法发生了 ...

  3. MIT 线性代数 Linear Algebra 9: 向量空间的一些定义(线性独立,基,维度)

    本节内容都是一些定义,实际上我们之前已经接触过了.让我们总结一下: linear independent 线性独立 给定一组向量 {v1,v2,...,vn}\{\bm{v_1,v_2,...,v_n ...

  4. 线性代数 -- Linear Algebra with Applications

    @.如果线性方程组无解,则称该方程组是不相容的(inconsistent). @.如果线性方程组至少存在一个解,则称该方程组是相容的(consistent). @.等价方程组(equivalent s ...

  5. MIT 线性代数 Linear Algebra 10: 矩阵的四个space

    这一节是相当于对之前所有内容的一个总括,也是对线性代数的研究对象 – 矩阵 – 的一个总结 (从vector space的角度). 这四个space分别是 Column space C ( A ) C ...

  6. 线性代数第九版pdf英文_《Linear Algebra Done Right》线性代数复习及部分习题解答(3.C)...

    个人声明 本系列文章记录本人自学线性代数教材<Linear Algebra Done Right>的概念梳理(复习)和部分习题解答(练习).如有任何错误或不严谨之处恳请读者在评论区留言提醒 ...

  7. GAMES101课程学习笔记—Lec 02:Linear Algebra 线性代数回顾

    GAMES101课程学习笔记-Lec 02:Linear Algebra 线性代数回顾 0 图形学的依赖学科 1 向量 1.1 点乘 1.2 叉乘 2 矩阵 本节课知识比较基础,大学课程里应该都学过, ...

  8. Linear Algebra 线性代数

    Linear Algebra 线性代数 最近在看Deep Learning这本书,刚看了Linear Algebra章,总结一下. 名词函数 Scalars:标量,就是单个数,一般用小写倾斜字体表示. ...

  9. 线性代数基本定理(核空间与行空间)——The Fundamental Theorem of Linear Algebra

    本文依据Nicholas Hoell的讲义The Fundamental Theorem of Linear Algebra翻译,水平有限,如有不当欢迎指正. 目录 一.预备知识:正交补空间 1.1 ...

最新文章

  1. mysql登录报错:ERROR 1045 (28000): Access denied for user root@localhost (using password: NO)
  2. css常用样式汇总记录
  3. Java 算法 S01串
  4. python使用布隆过滤器筛选数据
  5. 【LeetCode】【HOT】226. 翻转二叉树(递归)
  6. 考研c 语言程序设计题库,温州大学c语言程序设计考研复试核心题库(23页)-原创力文档...
  7. devc运行窗口不显示_编写Qt多窗口程序
  8. 如何写PRD (附PRD案例)
  9. 数字图像学笔记——8. 几种常见的空间滤波器(均值滤波器、中值滤波器)
  10. 解决 xftp 远程目录显示乱码
  11. 年近30,半失业状态:定制化,正在拖垮年轻人
  12. 全球及中国智能手机过滤器行业销售动态及投资盈利预测报告(2022-2027)
  13. 【Unity】 结合DoTween制作抛物线效果
  14. 包装类和自动拆箱与自动装箱
  15. Maven环境搭建及配置
  16. 【JavaSE】《基础篇005》集合
  17. Android 对接 dropbox Chooser
  18. Excel同时按照书名号和顿号分列成3列数据的操作
  19. 当GCN遇见NLP(三) Tensor Graph Convolutional Networks for Text Classification,AAAI2020
  20. comsol设置交流电信号

热门文章

  1. 远光九天云平台荣获“2021年度珠海市科技创新产品”
  2. 给公司代码分配会计年度变式(Fiscal Year Variant)
  3. 【STM32开发环境】Linux下开发stm32(二) | 使用openocd下载程序
  4. 红帽系统配置nginx自启动
  5. navicat连接远程服务器数据库教程
  6. 射频参数功率的单位dbm,db,mw
  7. 关于 HTTP 代理
  8. Python入门(上)
  9. java slf4j 占位符_slf4j 占位符
  10. 2023年全球及中国盐酸格拉司琼(试剂)行业头部企业市场占有率及排名调研报告