欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在python中的实现矩阵的乘法 、矩阵的转置、学习numpy中的矩阵运算方法

程序员文章站 2022-09-21 10:07:05
创建 矩阵类文件 Matrix.py创建 需要使用到的 矩阵函数功能from.Vector import Vectorclass Matrix: def __init__(self,list2d): self._values = [row[:]for row in list2d] def row_vector(self,index): '返回矩阵的第index个行向量' return Vector(self._values[index...

创建 矩阵类文件 Matrix.py
创建 需要使用到的 矩阵函数功能

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])  # 返回第0个元素即知道了有几列

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

    __str__ = __repr__ # 返回同样的字符串,不再进行区分 

与Vector相同,建立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('len(matrix) = {}'.format(len(matrix)))
    print('matrix[0][0] = {}'.format(matrix[0,0]))

# 输出结果为
Matrix([[1, 2], [3, 4]])
matrix.shape = (2, 2)
matrix.size = 4
len(matrix) = 2
matrix[0][0] = 1 

加入矩阵基本运算函数

@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(), \
            'Error in adding. Shape of matrix must be same'
        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 adding. Shape of matrix must be same'
        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):
        '返回矩阵的数量乘法结果: self * k'
        return Matrix([[e * k for e in self.row_vector(i)]
                       for i in range(self.row_num())])

    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 

验证函数功能

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

# 输出结果为
add: Matrix([[6, 8], [10, 12]])
subtract: Matrix([[-4, -4], [-4, -4]])
scalar-mul: Matrix([[2, 4], [6, 8]])
scalar-mul: Matrix([[2, 4], [6, 8]])
zero_2_3: Matrix([[0, 0, 0], [0, 0, 0]]) 

添加矩阵的乘法运算函数

 def dot(self, another):
        """返回矩阵乘法的结果"""
        if isinstance(another, Vector):
            # 矩阵和向量的乘法
            assert self.col_num() == len(another), \
                "Error in Matrix-Vector Multiplication."
            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 Matrix-Matrix Multiplication."
            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())]) 

验证函数

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

    # print("A.dot(B) = {}".format(matrix.dot(matrix2)))
    # print("B.dot(A) = {}".format(matrix2.dot(matrix))) 

添加转置功能

 def T(self):
        '返回矩阵的转置矩阵'
        return Matrix([[e for e in self.col_vector(i)]
                       for i in range(self.col_num())]) 

验证转置

print('P.T = {}'.format(P.T()))

# 输出结果
P.T = Matrix([[[0], [0]], [[4], [0]], [[5], [3]]]) 

学习使用numpy中的矩阵方法

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)) # 真正的矩阵相乘结果

    p = np.array([10,100])
    print(A + p) # 不适于线性代数中
    print(A + 1) # 广播,高维数组可以与低维数组相加,不适于线性代数中

    print(A.dot(p))

# 输出结果
[[1 2]
 [3 4]]
 
(2, 2)

[[1 3]
 [2 4]]
 
4

[1 2]
[1 3]
[3 4]

[[ 6  8]
 [10 12]]
 
[[-4 -4]
 [-4 -4]]
 
[[10 20]
 [30 40]]
 
[[10 20]
 [30 40]]
 
[[ 5 12]
 [21 32]]
 
[[19 22]
 [43 50]]
 
[[ 11 102]
 [ 13 104]]
 
[[2 3]
 [4 5]]
 
[210 430] 

本文地址:https://blog.csdn.net/IAN27/article/details/108240490

相关标签: 线性代数 python