人工智能必备数学知识学习笔记3:向量的基本运算
向量加法
几何意义:
基于二位向量运算:
基于三维向量运算:
多维向量运算:
向量乘法:
代码实现:
1. 在Vector.py编写代码
1 #向量类 2 #__values() 与 _values()区别更多体现在继承上,如果是在类的内部使用时官方建议使用_values()发方法 3 4 5 class Vector: 6 7 def __init__(self,lst): 8 self._values = list(lst)#将数组赋值给向量类中(注:使用list方法将列表lst复制一份保证他的不被外界调用时修改) 9 10 #向量加法,返回结果向量 11 def __add__(self, another): 12 # assert判断传入的向量维度是否相等 13 assert len(self) == len(another),\ 14 "Error in adding. Length of vectors must be same." 15 return Vector([a+b for a,b in zip(self,another)])#使用zip()方法将两个向量取出来 16 17 # 向量减法 18 def __sub__(self, another): 19 assert len(self) == len(another), \ 20 "Error in adding. Length of vectors must be same." 21 return Vector([a - b for a, b in zip(self, another)]) 22 23 # 向量乘法(数乘数组),返回数量乘法的结果向量:self * k 24 def __mul__(self, k): 25 return Vector([k * e for e in self]) 26 27 # 向量乘法(数组乘数),返回数量乘法的结果向量:k * self 28 def __rmul__(k, self): 29 return k * self #此处直接调用的是上方的乘法函数 30 31 #返回向量取正的结果向量 32 def __pos__(self): 33 return 1 * self 34 35 # 返回向量取负的结果向量 36 def __neg__(self): 37 return -1 * self 38 39 #返回向量迭代器(当有迭代器时,zip()方法中就不用再次传入两个向量数组,直接传入向量对象即可<zip(self._values,another._values)>) 40 def __iter__(self): 41 return self._values.__iter__() 42 43 #取向量的index个元素 44 def __getitem__(self, index): 45 return self._values[index] 46 47 #返回向量的长度(有多少个元素) 48 def __len__(self): 49 return len(self._values) 50 51 # 向量展示(系统调用) 52 def __repr__(self): 53 return "Vector({})".format(self._values) 54 55 # 向量展示(用户调用) 56 def __str__(self): 57 return "({})".format(", ".join(str(e) for e in self._values))#通过遍历 self.__values 将e转成字符串通过逗号加空格来链接放入大括号中 58 59 # u = Vector([5,2]) 60 # print(u)
2.在main_vector.py展示中编写:
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, 3 * vec)) # 向量取正 print("+{} = {}".format(vec, +vec)) # 向量取负 print("-{} = {}".format(vec, -vec))
3.运行main_vector.py结果为:
1 /Users/liuxiaoming/PycharmProjects/LinearAlgebra/venv/bin/python /Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py --mode=client --port=51606 2 import sys; print('Python %s on %s' % (sys.version, sys.platform)) 3 sys.path.extend(['/Users/liuxiaoming/PycharmProjects/LinearAlgebra']) 4 PyDev console: starting. 5 Python 3.8.2 (v3.8.2:7b3ab5921f, Feb 24 2020, 17:52:18) 6 [Clang 6.0 (clang-600.0.57)] on darwin 7 >>> runfile('/Users/liuxiaoming/PycharmProjects/LinearAlgebra/main_vector.py', wdir='/Users/liuxiaoming/PycharmProjects/LinearAlgebra') 8 (5, 2) 9 2 10 vec[0] = 5, vec[1] = 2 11 (5, 2) + (3, 1) = (8, 3) 12 (5, 2) - (3, 1) = (2, 1) 13 (5, 2) * 3 = (15, 6) 14 3 * (5, 2) = (15, 6) 15 +(5, 2) = (5, 2) 16 -(5, 2) = (-5, -2)