Skip to content

Commit

Permalink
Chapter 04 restructured.
Browse files Browse the repository at this point in the history
  • Loading branch information
liuyubobobo committed Jul 31, 2018
1 parent 25faa0d commit 103a0f2
Show file tree
Hide file tree
Showing 15 changed files with 255 additions and 6 deletions.
11 changes: 11 additions & 0 deletions 04-The-Matrix/02-Implement-Our-Own-Matrix/main_matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
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("len(matrix) = {}".format(len(matrix)))
print("matrix[0][0] = {}".format(matrix[0, 0]))
44 changes: 44 additions & 0 deletions 04-The-Matrix/02-Implement-Our-Own-Matrix/playLA/Matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from .Vector import Vector


class Matrix:

def __init__(self, list2d):
self._values = [row[:] for row in list2d]

def row_vector(self, index):
"""返回矩阵的第index个行向量"""
return Vector(self._values[index])

def col_vector(self, index):
"""返回矩阵的第index个列向量"""
return Vector([row[index] for row in self._values])

def __getitem__(self, pos):
"""返回矩阵pos位置的元素"""
r, c = pos
return self._values[r][c]

def size(self):
"""返回矩阵的元素个数"""
r, c = self.shape()
return r * c

def row_num(self):
"""返回矩阵的行数"""
return self.shape()[0]

__len__ = row_num

def col_num(self):
"""返回矩阵的列数"""
return self.shape()[1]

def shape(self):
"""返回矩阵的形状: (行数, 列数)"""
return len(self._values), len(self._values[0])

def __repr__(self):
return "Matrix({})".format(self._values)

__str__ = __repr__
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
print(matrix)
print("matrix.shape = {}".format(matrix.shape()))
print("matrix.size = {}".format(matrix.size()))
print("len(matrix) = {}".format(len(matrix)))
print("matrix[0][0] = {}".format(matrix[0, 0]))

matrix2 = Matrix([[5, 6], [7, 8]])
print(matrix2)
print("add: {}".format(matrix + matrix2))
print("substract: {}".format(matrix - matrix2))
print("subtract: {}".format(matrix - matrix2))
print("scalar-mul: {}".format(2 * matrix))
print("scalar-mul: {}".format(matrix * 2))
print("zero_2_3: {}".format(Matrix.zero(2, 3)))
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import numpy as np

if __name__ == "__main__":

print(np.__version__)

# np.array 基础
lst = [1, 2, 3]
lst[0] = "Linear Algebra"
print(lst)

vec = np.array([1, 2, 3])
print(vec)
# vec[0] = "Linear Algebra"
# vec[0] = 666
# print(vec)

# np.array的创建
print(np.zeros(5))
print(np.ones(5))
print(np.full(5, 666))

# np.array的基本属性
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]))

# np.array的基本运算
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, 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)))

# zero3 = np.zeros(3)
# print(zero3 / np.linalg.norm(zero3))
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from playLA.Vector import Vector

if __name__ == "__main__":

vec = Vector([5, 2])
print(vec)
print("len(vec) = {}".format(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))

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

print("norm({}) = {}".format(vec, vec.norm()))
print("norm({}) = {}".format(vec2, vec2.norm()))
print("norm({}) = {}".format(zero2, zero2.norm()))

print("normalize {} is {}".format(vec, vec.normalize()))
print(vec.normalize().norm())

print("normalize {} is {}".format(vec2, vec2.normalize()))
print(vec2.normalize().norm())

try:
zero2.normalize()
except ZeroDivisionError:
print("Cannot normalize zero vector {}.".format(zero2))

print(vec.dot(vec2))
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ class Matrix:
def __init__(self, list2d):
self._values = [row[:] for row in list2d]

@classmethod
def zero(cls, r, c):
"""返回一个r行c列的零矩阵"""
return cls([[0] * c for _ in range(r)])

def __add__(self, another):
"""返回两个矩阵的加法结果"""
assert self.shape() == another.shape(), \
Expand All @@ -29,6 +34,18 @@ def __rmul__(self, k):
"""返回矩阵的数量乘结果: k * self"""
return self * k

def __truediv__(self, k):
"""返回数量除法的结果矩阵:self / k"""
return (1 / k) * self

def __pos__(self):
"""返回矩阵取正的结果"""
return 1 * self

def __neg__(self):
"""返回矩阵取负的结果"""
return -1 * self

def row_vector(self, index):
"""返回矩阵的第index个行向量"""
return Vector(self._values[index])
Expand All @@ -47,12 +64,12 @@ def size(self):
r, c = self.shape()
return r * c

__len__ = size

def row_num(self):
"""返回矩阵的行数"""
return self.shape()[0]

__len__ = row_num

def col_num(self):
"""返回矩阵的列数"""
return self.shape()[1]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import math
from ._globals import EPSILON


class Vector:

def __init__(self, lst):
self._values = list(lst)

@classmethod
def zero(cls, dim):
"""返回一个dim维的零向量"""
return cls([0] * dim)

def __add__(self, another):
"""向量加法,返回结果向量"""
assert len(self) == len(another), \
"Error in adding. Length of vectors must be same."

return Vector([a + b for a, b in zip(self, another)])

def __sub__(self, another):
"""向量减法,返回结果向量"""
assert len(self) == len(another), \
"Error in subtracting. Length of vectors must be same."

return Vector([a - b for a, b in zip(self, another)])

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

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

def __mul__(self, k):
"""返回数量乘法的结果向量:self * k"""
return Vector([k * e for e in self])

def __rmul__(self, k):
"""返回数量乘法的结果向量:k * self"""
return self * k

def __truediv__(self, k):
"""返回数量除法的结果向量:self / k"""
return (1 / k) * self

def __pos__(self):
"""返回向量取正的结果向量"""
return 1 * self

def __neg__(self):
"""返回向量取负的结果向量"""
return -1 * self

def __iter__(self):
"""返回向量的迭代器"""
return self._values.__iter__()

def __getitem__(self, index):
"""取向量的第index个元素"""
return self._values[index]

def __len__(self):
"""返回向量长度(有多少个元素)"""
return len(self._values)

def __repr__(self):
return "Vector({})".format(self._values)

def __str__(self):
return "({})".format(", ".join(str(e) for e in self._values))
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from ._globals import EPSILON
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
EPSILON = 1e-8
13 changes: 10 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,17 @@
| 3-5 实现向量的点乘操作 | 实现 | [Python](03-More-about-Vectors/05-Implementations-of-Dot-Product/) |
| 3-6 向量点乘的应用 | 原理 | - |
| 3-7 Numpy中向量的基本使用 | 实现 | [Python](03-More-about-Vectors/07-Vectors-in-Numpy/) |
| **第四章 矩阵不只是m\*n个数字** | - | [04-The-Matrix/] |
| **第四章 矩阵不只是m\*n个数字** | - | [章节文件夹](04-The-Matrix/) |
| 4-1 什么是矩阵 | 原理 | - |
| 4-2 矩阵的基本运算和基本性质 | 原理 | - |
| 4-3 实现属于我们自己的矩阵类 | 实现 | [Python](04-The-Matrix/03-Vectors-in-Numpy/) |
| 4-2 实现属于我们自己的矩阵类 | 实现 | [Python](04-The-Matrix/02-Implement-Our-Own-Matrix/) |
| 4-3 矩阵的基本运算和基本性质 | 原理 | - |
| 4-4 实现矩阵的基本运算 | 实现 | [Python](04-The-Matrix/04-Implement-Basic-Operations-of-Matrix/) |
| 4-5 矩阵和向量的乘法 | 原理 | - |
| 4-6 矩阵和矩阵的乘法及性质 | 原理 | - |
| 4-7 实现矩阵的乘法 | 实现 | [Python] |
| 4-8 矩阵的转置和矩阵的逆 | 原理 | - |
| 4-9 矩阵的转置和矩阵逆的性质 | 原理 | - |
| 4-10 实现矩阵的转置 | 实现 | [Python] |
| **第五章 矩阵的应用** | - | [更新中,敬请期待] |
| | | |
| **第六章 线性系统** | - | [更新中,敬请期待] |
Expand Down

0 comments on commit 103a0f2

Please sign in to comment.