美文网首页
NumPy 和线性代数

NumPy 和线性代数

作者: 蜗牛是不是牛 | 来源:发表于2022-09-13 15:46 被阅读0次

    本文主要介绍如何使用 Python 模块 NumPy 进行矩阵计算,并作为在伯克利学习或将学习 EECS 16A 的人的参考。

    什么是 NumPy?

    NumPy 是用于科学计算的库。据官网介绍,

    NumPy 是 Python 中科学计算的基础包。它是一个 Python 库,提供多维数组对象、各种派生对象(例如掩码数组和矩阵)以及用于对数组进行快速操作的各种例程,包括数学、逻辑、形状操作、排序、选择、I/O 、离散傅里叶变换、基本线性代数、基本统计运算、随机模拟等等。

    如何导入 NumPy

    要开始 Numpy 之旅,我们需要先导入 NumPy。下面的代码将 NumPy 库作为np.

    # install NumPy and named 'np'
    import numpy as np
    
    

    创建 NumPy 数组对象

    NumPy 数组对象与 Python List 非常相似(对 List 的引用)。然而,与 Python List 不同的是,某些方法不支持 NumPy(例如 sort() 和 reverse())。在 Numpy 中,向量和矩阵都存储在ndarray(※ N 维数组的缩写)中。但是,使用强制转换,您可以使用 Python List 方法或 NumPy 方法。有多种方法可以使用 NumPy 创建矩阵。

    示例 1(创建矩阵array()

    创建可迭代对象并将其插入到 NumPy 数组中array()

    数组()参考

    # normal Python List
    list = [1, 2, 3, 4, 5]
    # normal Python Tuple
    tup = ((1, 2, 3, 4, 5), (6, 7, 8, 9, 10))
    
    # NumPy Array object
    mtx1 = np.array(list)
    mtx2 = np.array(tup)
    
    print("list :\n", list)
    print("mtx1 :\n", mtx1)
    
    print("tup :\n", tup)
    print("mtx2 :\n", mtx2)
    
    
    # output
    list :
     [1, 2, 3, 4, 5]
    mtx1 :
     [1 2 3 4 5]
    tup :
     ((1, 2, 3, 4, 5), (6, 7, 8, 9, 10))
    mtx2 :
     [[ 1  2  3  4  5]
     [ 6  7  8  9 10]]
    
    

    示例 2(使用 插入每个组件empty()

    使用empty([<SIZE OF ROW>, <SIZE OF COLMN>])可以创建空的 NumPy 数组,也可以使用dtype关键字来限制数据类型。但是,由 empty() 创建的数组本身设置了完全随机数,您需要对其进行初始化。

    mtx = np.empty([3,3])
    for i in range(3):
        for j in range(3):
            mtx[i, j] = i + j # initializing Numpy Array.
    
    print("mtx: \n", mtx)
    
    
    mtx: 
     [[0\. 1\. 2.]
     [1\. 2\. 3.]
     [2\. 3\. 4.]]
    
    

    Example3(标识数组eye()和全零数组zeros()

    在某些情况下,有一种更简单的方法来创建数组。例如,要创建一个恒等数组,一个对角元素为 1,其他元素为 0,其中所有对角元素为 1eye()的方阵,比创建数组并将所有元素对角线初始化为 1 简单得多。此外,零向量零矩阵,其中所有分量为零的向量或矩阵,可以使用创建zeros()

    eye() 参考
    zeros() 参考

    # to create identity matrix
    identity_mtx = np.eye(5)
    print("identity matrix\n", identity_mtx)
    
    # to create zeros matrix
    zero_mtx = np.zeros([5,5])
    print("zeros matrix\n",zero_mtx)
    
    
    # output
    identity matrix
     [[1\. 0\. 0\. 0\. 0.]
     [0\. 1\. 0\. 0\. 0.]
     [0\. 0\. 1\. 0\. 0.]
     [0\. 0\. 0\. 1\. 0.]
     [0\. 0\. 0\. 0\. 1.]]
    zeros matrix
     [[0\. 0\. 0\. 0\. 0.]
     [0\. 0\. 0\. 0\. 0.]
     [0\. 0\. 0\. 0\. 0.]
     [0\. 0\. 0\. 0\. 0.]
     [0\. 0\. 0\. 0\. 0.]]
    
    

    NumPy 数组上的广播算术操作

    通过使用 NumPy 模块,您不再需要手动计算矩阵。

    import numpy as np
    mtx = np.array([[1,1,1], [1,1,1], [1,1,1], [1,1,1]])
    
    print("mtx\n", mtx)
    
    print("mtx1 + 10\n", mtx + 10) # addtion
    print("mtx2 - 1\n", mtx - 1) # substitution
    print("mtx1 * 10\n", mtx * 10) # multiplication
    print("mtx2 / 10\n", mtx / 10) # division
    
    
    # output
    mtx
     [[1 1 1]
     [1 1 1]
     [1 1 1]
     [1 1 1]]
    mtx1 + 10
     [[11 11 11]
     [11 11 11]
     [11 11 11]
     [11 11 11]]
    mtx2 - 1
     [[0 0 0]
     [0 0 0]
     [0 0 0]
     [0 0 0]]
    mtx1 * 10
     [[10 10 10]
     [10 10 10]
     [10 10 10]
     [10 10 10]]
    mtx2 / 10
     [[0.1 0.1 0.1]
     [0.1 0.1 0.1]
     [0.1 0.1 0.1]
     [0.1 0.1 0.1]]
    
    

    访问 NumPy 数组的元素

    始终提醒您,数组索引以0开头,并且不包括行或列的末尾。

    import numpy as np
    
    mtx = np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]])
    
    print("original matrix\n", mtx)
    
    # Accessing the first row
    print("Accessing the first row\n", mtx[0])
    # Accessing the second col
    print("Accessing the second col\n", mtx[:,1])
    # Accesing the element at 2nd col and 2nd row
    print("Accesing the element at 2nd col and 2nd row\n", mtx[1, 1])
    # Accessing the matrix at 1-2 col and 1-2 row
    print("Accessing the matrix at 1-2 col and 1-2 row\n", mtx[:2, :2]) 
    # becareful the end of col or row is not included
    
    
    # output
    original matrix
     [[1 2 3]
     [4 5 6]
     [7 8 9]]
    Accessing the first row
     [1 2 3]
    Accessing the second col
     [2 5 8]
    Accesing the element at 2nd col and 2nd row
     5
    Accessing the matrix at 1-2 col and 1-2 row
     [[1 2]
     [4 5]]
    
    

    点积(内积)

    利用np.dot(), 可以轻松解决烦人的矩阵点积问题。但是,要计算矩阵,必须匹配内部维度。

    import numpy as np
    
    a = np.array([[1, 2, 3],[4, 5, 6]])
    b = np.array([[1, 2],[3, 4],[5, 6]])
    
    print('the dot product of a and b\n', np.dot(a, b))
    
    
    # output
    the dot product of a and b
     [[22 28]
     [49 64]]
    
    

    转置

    转换原始矩阵的行和列的矩阵称为矩阵的转置。例如,矩阵 m × n 的转置为 n × m。

    import numpy as np
    
    mtx = np.array([[1, 2, 3], [4, 5, 6]])
    print("original matrix\n", mtx)
    
    transposed = np.transpose(mtx)
    
    print("transposed matrix\n", transposed)
    
    
    # output
    
    original matrix
     [[1 2 3]
     [4 5 6]]
    transposed matrix
     [[1 4]
     [2 5]
     [3 6]]
    
    

    逆函数

    col 和 row 相同的矩阵称为方阵。只有一个矩阵,使得某个方阵与它的点积为单位矩阵,该矩阵称为逆矩阵。通常,手动找到矩阵的逆矩阵非常困难。但是,np.linalg.inv()有助于找到矩阵的逆矩阵。

    import numpy as np
    
    mtx = np.array([[1, 2], [3, 4]])
    
    inversed = np.linalg.inv(mtx)
    
    print("original matrix\n", mtx)
    
    print("inverse matrix\n",inversed)
    
    print("the dot product of the original matrix and inverse matrix\n",np.dot(mtx, inversed))
    
    
    # output
    
    original matrix
     [[1 2]
     [3 4]]
    inverse matrix
     [[-2\.   1\. ]
     [ 1.5 -0.5]]
    the dot product of the original matrix and inverse matrix
     [[1.0000000e+00 0.0000000e+00]
     [8.8817842e-16 1.0000000e+00]]
    
    

    文章来源:https://kojiro.hashnode.dev/numpy-and-linear-algebra

    相关文章

      网友评论

          本文标题:NumPy 和线性代数

          本文链接:https://www.haomeiwen.com/subject/mzxlortx.html