搜索
首页后端开发Python教程如何在Python中求逆矩阵或nArray?

如何在Python中求逆矩阵或nArray?

在本文中,我们将向您展示如何使用 Python 中的 NumPy 库计算矩阵或 ndArray 的逆。

什么是矩阵的逆矩阵?

矩阵的逆矩阵是这样的,如果它乘以原始矩阵,就会得到单位矩阵。

矩阵的逆只是矩阵的倒数,就像在常规算术中一样,对于用于求解方程以获得未知变量值的单个数字。矩阵的逆矩阵是与原始矩阵相乘时生成单位矩阵的矩阵。

只有当矩阵是非奇异的,即行列式不为0时,矩阵的逆才存在。我们可以使用下面的公式,使用行列式和伴随矩阵来简单地找到方阵的逆

if det(A) != 0
 A-1 = adj(A)/det(A)
else
 "Inverse does not exist"

方法 1 - 对 np.array() 类型使用 numpy.linalg.inv() 函数

numpy.linalg.inv() 函数

Python 有一个非常简单的方法来计算矩阵的逆。要计算矩阵的逆,请使用 Python 中 NumPy 模块中的 numpy.linalg.inv() 函数绕过矩阵。

语法

numpy.linalg.inv(array)

参数

array - 它是必须反转的矩阵。

返回值 - numpy.linalg.inv() 函数返回矩阵的逆矩阵。

算法(步骤)

以下是执行所需任务所需遵循的算法/步骤 -

  • 使用 import 关键字,导入带有别名 (np) 的 numpy 模块。

  • 使用numpy.array()函数(返回一个ndarray。ndarray是满足给定要求的数组对象),通过传递3维数组来创建numpy数组array(3rows, 3columns) 作为它的参数。

  • 使用 numpy 模块的 linalg.inv() 函数(计算矩阵的逆)通过将输入矩阵作为参数传递来计算输入 3x3 矩阵的逆并打印逆矩阵。

示例

以下程序使用 numpy.linalg.inv() 函数返回输入 3 维 (3x3) 矩阵的逆矩阵 -

# importing numpy module with an alias name
import numpy as np

# creating a 3-Dimensional(3x3) numpy matrix
inputArray_3d = np.array([[4, 5, 1],
   [3, 4, 12],
   [10, 2, 1]])

# printing the input 3D matrix
print("The input numpy 3D matrix:")
print(inputArray_3d)

# calculating the inverse of an input 3D matrix
resultInverse= np.linalg.inv(inputArray_3d)

# printing the resultant inverse of an input matrix
print("The Inverse of 3-Dimensional(3x3) numpy matrix:")
print(resultInverse)

输出

执行时,上述程序将生成以下输出 -

The input numpy 3D matrix:
[[ 4  5  1]
 [ 3  4 12]
 [10  2  1]]
The Inverse of 3-Dimensional(3x3) numpy matrix:
[[-0.04246285 -0.00636943  0.11889597]
 [ 0.24840764 -0.01273885 -0.0955414 ]
 [-0.07218684  0.08917197  0.00212314]]

方法 2 - 使用 scipy.linalg.inv() 函数

scipy.linalg.inv()

使用 scipy 模块的功能,我们可以执行各种科学计算。它也适用于 numpy 数组。

在Python中,scipy.linalg.inv()还可以返回给定方阵的逆矩阵。它的工作方式与 numpy.linalg.inv() 函数相同。

算法(步骤)

以下是执行所需任务所需遵循的算法/步骤 -

  • 使用 import 关键字,从 scipy 模块导入 linalg。

  • 使用numpy.matrix()函数(从数据字符串或类似数组的对象返回矩阵。生成的矩阵是一个专门的二维数组),用于创建numpy 矩阵,通过将二维数组(2行,2列)作为参数传递给它。

  • 使用 scipy 模块的 linalg.inv() 函数(计算矩阵的逆)通过将输入矩阵作为参数传递来计算输入 2x2 矩阵的逆并打印逆矩阵。

    示例

    import numpy as np
    # importing linalg from scipy module
    from scipy import linalg
    
    # creating a 2-Dimensional(2x2) NumPy matrix
    inputMatrix = np.matrix([[5, 2],[7, 3]])
    
    # printing the input 2D matrix
    print("The input numpy 2D matrix:")
    print(inputMatrix)
    
    # calculating the inverse of an input 2D matrix
    resultInverse = linalg.inv(inputMatrix)
    
    # printing the resultant inverse of an input matrix
    print("The Inverse of 2-Dimensional(2x2) numpy matrix:")
    print(resultInverse)
    

    输出

    The input numpy 2D matrix:
    [[5 2]
    [7 3]]
    The Inverse of 2-Dimensional(2x2) numpy matrix:
    [[ 3. -2.]
    [-7. 5.]]
    

    方法 3 - 对 np.matrix() 类型使用 numpy.linalg.inv() 函数

    算法(步骤)

    以下是执行所需任务所需遵循的算法/步骤 -

    • 使用 numpy.matrix() 函数(从数据字符串或类似数组的对象返回矩阵。生成的矩阵是一个专门的 4D 数组),用于创建numpy 矩阵,通过将 4 维数组(4 行,4 列)作为参数传递给它。

      示例

      import numpy as np
      
      # creating a NumPy matrix (4x4 matrix) using matrix() method
      inputMatrix = np.matrix('[11, 1, 8, 2; 11, 3, 9 ,1; 1, 2, 3, 4; 9, 8, 7, 6]')
      
      # printing the input 4D matrix
      print("The input NumPy matrix:")
      print(inputMatrix)
      
      # calculating the inverse of an input matrix
      resultInverse= np.linalg.inv(inputMatrix)
      
      # printing the resultant inverse of an input matrix
      print("The Inverse of 4-Dimensional(4x4) numpy matrix:")
      print(resultInverse)
      

      输出

      The input NumPy matrix:
      [[11 1 8 2]
      [11 3 9 1]
      [ 1 2 3 4]
      [ 9 8 7 6]]
      The Inverse of 4-Dimensional(4x4) numpy matrix:
      [[ 0.25   -0.23214286   -0.24107143   0.11607143]
      [-0.25     0.16071429   -0.09464286   0.11964286]
      [-0.25     0.375         0.3125      -0.1875    ]
      [ 0.25    -0.30357143    0.12321429   0.05178571]]
      

      结论

      在本文中,我们学习了如何使用三个不同的示例来计算矩阵的逆。我们学习了如何使用两种不同的方法在 Numpy 中获取矩阵:numpy.array() 和 NumPy.matrix()。

      以上是如何在Python中求逆矩阵或nArray?的详细内容。更多信息请关注PHP中文网其他相关文章!

      声明
      本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
      Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

      pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

      Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

      pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

      对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

      在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

      循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

      ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

      Python:它是真正的解释吗?揭穿神话Python:它是真正的解释吗?揭穿神话May 12, 2025 am 12:05 AM

      pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

      与同一元素的Python串联列表与同一元素的Python串联列表May 11, 2025 am 12:08 AM

      concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

      解释与编译语言:Python的位置解释与编译语言:Python的位置May 11, 2025 am 12:07 AM

      pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

      循环时:您什么时候在Python中使用?循环时:您什么时候在Python中使用?May 11, 2025 am 12:05 AM

      Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

      See all articles

      热AI工具

      Undresser.AI Undress

      Undresser.AI Undress

      人工智能驱动的应用程序,用于创建逼真的裸体照片

      AI Clothes Remover

      AI Clothes Remover

      用于从照片中去除衣服的在线人工智能工具。

      Undress AI Tool

      Undress AI Tool

      免费脱衣服图片

      Clothoff.io

      Clothoff.io

      AI脱衣机

      Video Face Swap

      Video Face Swap

      使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

      热门文章

      热工具

      SublimeText3 Linux新版

      SublimeText3 Linux新版

      SublimeText3 Linux最新版

      ZendStudio 13.5.1 Mac

      ZendStudio 13.5.1 Mac

      功能强大的PHP集成开发环境

      SecLists

      SecLists

      SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

      WebStorm Mac版

      WebStorm Mac版

      好用的JavaScript开发工具

      PhpStorm Mac 版本

      PhpStorm Mac 版本

      最新(2018.2.1 )专业的PHP集成开发工具