在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础。
numpy中创建单位矩阵借助identity()函数。更为准确的说,此函数创建的是一个n*n的单位数组,返回值的dtype=array数据形式。其中接受的参数有两个,第一个是n值大小,第二个为数据类型,一般为浮点型。单位数组的概念与单位矩阵相同,主对角线元素为1,其他元素均为零,等同于单位1。而要想得到单位矩阵,只要用mat()函数将数组转换为矩阵即可。

>>> import numpy as np
>>> help(np.identity)Help on function identity in module numpy:identity(n, dtype=None)Return the identity array.The identity array is a square array with ones onthe main diagonal.Parameters----------n : intNumber of rows (and columns) in `n` x `n` output.dtype : data-type, optionalData-type of the output.  Defaults to ``float``.Returns-------out : ndarray`n` x `n` array with its main diagonal set to one,and all other elements 0.Examples-------->>> np.identity(3)array([[ 1.,  0.,  0.],[ 0.,  1.,  0.],[ 0.,  0.,  1.]])
>>> np.identity(5)array([[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.]])
>>> A = np.mat(np.identity(5))>>> Amatrix([[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.]])

矩阵的运算中还经常使用对角阵,numpy中的对角阵用eye()函数来创建。eye()函数接受五个参数,返回一个单位数组。第一个和第二个参数N,M分别对应表示创建数组的行数和列数,当然当你只设定一个值时,就默认了N=M。第三个参数k是对角线指数,跟diagonal中的offset参数是一样的,默认值为0,就是主对角线的方向,上三角方向为正,下三角方向为负,可以取-n到+m的范围。第四个参数是dtype,用于指定元素的数据类型,第五个参数是order,用于排序,有‘C’和‘F’两个参数,默认值为‘C’,为行排序,‘F’为列排序。返回值为一个单位数组。

>>> help(np.eye)Help on function eye in module numpy:eye(N, M=None, k=0, dtype=<class 'float'>, order='C')Return a 2-D array with ones on the diagonal and zeros elsewhere.Parameters----------N : intNumber of rows in the output.M : int, optionalNumber of columns in the output. If None, defaults to `N`.k : int, optionalIndex of the diagonal: 0 (the default) refers to the main diagonal,a positive value refers to an upper diagonal, and a negative valueto a lower diagonal.dtype : data-type, optionalData-type of the returned array.order : {'C', 'F'}, optionalWhether the output should be stored in row-major (C-style) orcolumn-major (Fortran-style) order in memory... versionadded:: 1.14.0Returns-------I : ndarray of shape (N,M)An array where all elements are equal to zero, except for the `k`-thdiagonal, whose values are equal to one.See Also--------identity : (almost) equivalent functiondiag : diagonal 2-D array from a 1-D array specified by the user.Examples-------->>> np.eye(2, dtype=int)array([[1, 0],[0, 1]])>>> np.eye(3, k=1)array([[ 0.,  1.,  0.],[ 0.,  0.,  1.],[ 0.,  0.,  0.]])

numpy中的diagonal()方法可以对n*n的数组和方阵取对角线上的元素,diagonal()接受三个参数。第一个offset参数是主对角线的方向,默认值为0是主对角线,上三角方向为正,下三角方向为负,可以取-n到+n的范围。第二个参数和第三个参数是在数组大于2维时指定一个2维数组时使用,默认值axis1=0,axis2=1。

>>> help(A.diagonal)Help on built-in function diagonal:diagonal(...) method of numpy.matrix instancea.diagonal(offset=0, axis1=0, axis2=1)Return specified diagonals. In NumPy 1.9 the returned array is aread-only view instead of a copy as in previous NumPy versions.  Ina future version the read-only restriction will be removed.Refer to :func:`numpy.diagonal` for full documentation.See Also--------numpy.diagonal : equivalent function
>>> help(np.diagonal)Help on function diagonal in module numpy:diagonal(a, offset=0, axis1=0, axis2=1)Return specified diagonals.If `a` is 2-D, returns the diagonal of `a` with the given offset,i.e., the collection of elements of the form ``a[i, i+offset]``.  If`a` has more than two dimensions, then the axes specified by `axis1`and `axis2` are used to determine the 2-D sub-array whose diagonal isreturned.  The shape of the resulting array can be determined byremoving `axis1` and `axis2` and appending an index to the right equalto the size of the resulting diagonals.In versions of NumPy prior to 1.7, this function always returned a new,independent array containing a copy of the values in the diagonal.In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,but depending on this fact is deprecated. Writing to the resultingarray continues to work as it used to, but a FutureWarning is issued.Starting in NumPy 1.9 it returns a read-only view on the original array.Attempting to write to the resulting array will produce an error.In some future release, it will return a read/write view and writing tothe returned array will alter your original array.  The returned arraywill have the same type as the input array.If you don't write to the array returned by this function, then you canjust ignore all of the above.If you depend on the current behavior, then we suggest copying thereturned array explicitly, i.e., use ``np.diagonal(a).copy()`` insteadof just ``np.diagonal(a)``. This will work with both past and futureversions of NumPy.Parameters----------a : array_likeArray from which the diagonals are taken.offset : int, optionalOffset of the diagonal from the main diagonal.  Can be positive ornegative.  Defaults to main diagonal (0).axis1 : int, optionalAxis to be used as the first axis of the 2-D sub-arrays from whichthe diagonals should be taken.  Defaults to first axis (0).axis2 : int, optionalAxis to be used as the second axis of the 2-D sub-arrays fromwhich the diagonals should be taken. Defaults to second axis (1).Returns-------array_of_diagonals : ndarrayIf `a` is 2-D, then a 1-D array containing the diagonal and of thesame type as `a` is returned unless `a` is a `matrix`, in which casea 1-D array rather than a (2-D) `matrix` is returned in order tomaintain backward compatibility.If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`are removed, and a new axis inserted at the end corresponding to thediagonal.Raises------ValueErrorIf the dimension of `a` is less than 2.See Also--------diag : MATLAB work-a-like for 1-D and 2-D arrays.diagflat : Create diagonal arrays.trace : Sum along diagonals.Examples-------->>> a = np.arange(4).reshape(2,2)>>> aarray([[0, 1],[2, 3]])>>> a.diagonal()array([0, 3])>>> a.diagonal(1)array([1])A 3-D example:>>> a = np.arange(8).reshape(2,2,2); aarray([[[0, 1],[2, 3]],[[4, 5],[6, 7]]])>>> a.diagonal(0, # Main diagonals of two arrays created by skipping...            0, # across the outer(left)-most axis last and...            1) # the "middle" (row) axis first.array([[0, 6],[1, 7]])The sub-arrays whose main diagonals we just obtained; note that eachcorresponds to fixing the right-most (column) axis, and that thediagonals are "packed" in rows.>>> a[:,:,0] # main diagonal is [0 6]array([[0, 2],[4, 6]])>>> a[:,:,1] # main diagonal is [1 7]array([[1, 3],[5, 7]])
>>> A = np.random.randint(low=5, high=30, size=(5, 5))>>> Aarray([[25, 15, 26,  6, 22],[27, 14, 22, 16, 21],[22, 17, 10, 14, 25],[11,  9, 27, 20,  6],[24, 19, 19, 26, 14]])
>>> A.diagonal()array([25, 14, 10, 20, 14])
>>> A.diagonal(offset=1)array([15, 22, 14,  6])
>>> A.diagonal(offset=-2)array([22,  9, 19])

numpy创建单位矩阵和对角矩阵相关推荐

  1. python矩阵对角化_numpy创建单位矩阵和对角矩阵的实例

    在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础. numpy中创建单位矩阵借助identity()函数.更为准确的说,此函数 ...

  2. python 对角阵_numpy创建单位矩阵和对角矩阵的实例

    在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础. numpy中创建单位矩阵借助identity()函数.更为准确的说,此函数 ...

  3. python 对角矩阵_numpy创建单位矩阵和对角矩阵的实例

    在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础. numpy中创建单位矩阵借助identity()函数.更为准确的说,此函数 ...

  4. python生成单位矩阵_numpy创建单位矩阵和对角矩阵的实例

    在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础. numpy中创建单位矩阵借助identity()函数.更为准确的说,此函数 ...

  5. numpy 创建加一行_Python数据分析快速入门--NumPy amp; Pandas

    之前为大家分享了python的基本语法,有疑问的小伙伴可以参考下文- 土豆爱数学:零基础如何快速入门python​zhuanlan.zhihu.com 对python基本语法了解后,就可以尝试用pyt ...

  6. numpy 创建加一行_数据科学|可视化图解Python科学计算包Numpy

    文章申明 文章作者:梁斌伟 责任编辑:郭德真 微信编辑:玖蓁 本文转载自公众号 实战统计学 (ID:statrcn) 原文链接:可视化图解Python科学计算包NumPy 作者:梁斌伟 编者按: 你真 ...

  7. numpy 创建加一行_NumPy数据处理的可视化

    NumPy库是Python库中用于数据分析,机器学习,科学计算的一个主力,它极大地简化了向量和矩阵的操作和处理.Python的一些主要软件包依赖于NumPy作为其架构的基础部分,比如scikit-le ...

  8. Python中的Numpy模块(1,numpy创建)

    1.什么是Numpy? Numpy   (Numeric Python) Numpy系统是Python中的一种开源的数值计算扩展. (1)   一个强大的N维数组对象Array (2)   比较成熟的 ...

  9. [转载] 使用python 中的numpy创建数组

    参考链接: Numpy 创建数组 使用nump创建数组的方法: (1)导入numpy模块: import numpy as np 注意:如果是纯python,默认是不安装numpy库的,需要在pyth ...

  10. 第一篇 使用numpy创建数组(一维、多维)

    1.numpy创建一维数组 [ 1] 通过列表生成数组 import numpy as np data1=[5,7,9,20]#列表类型 list arr1=np.array(data1) #ndar ...

最新文章

  1. tomcat报错LifecycleException的解决方案
  2. Redis入门(二)安装和基本操作
  3. input 模糊搜索
  4. VWware安装ubuntu设置静态IP
  5. 【Linux系统编程学习】Linux线程控制原语
  6. Python 解决面试题47 不用加减乘除做加法
  7. Core Graphics Paths
  8. linux内存管理之DMA
  9. FreeImage通用图像加载实现
  10. 大学生数学竞赛辅导:Stolz定理和f(x)≡0
  11. Oracle新创建的用户没有被授权user lacks CREATE SESSION privilege logon denied
  12. 51单片机学习笔记(郭天祥版)(5)——作业讲解、独立键盘、矩阵键盘
  13. 如何下载网页中的视频成mp4格式
  14. CSDN博客导出chm格式文档
  15. 关于I2C调试过程中遇到的一些细节性的问题(包括定位Master read-->Slaver send不成功的问题)
  16. 电源防反接电路 供电自动切换电路 - MOS管体二极管的应用
  17. go-pitaya学习笔记(12) - 看一看火龙果内置模块
  18. 浅析STM32H7 FDCAN(二)
  19. python爬取文章_[Python]爬取微信公众号文章
  20. python xlwt图表_python自动化办公(3)——Excel一键创建图表

热门文章

  1. CSS3+JavaScript效果:胶卷式放映
  2. 透过顶级机构Q2持仓报告看美股不同板块的行情
  3. 快来看,数据分析BI软件居然也能完成基金变迁大数据分析?
  4. Windows操作系统进阶:防火墙基础和Windows Defender
  5. 【问题解决】This scheduler instance is still active but was recovered by another instance in the cluster.
  6. 2018 *精读书单 -选读
  7. RGBA(0,0,0,0)调色
  8. double d C语言,1,若有以下定义,char a;int b;float c;double d;... 若有以下语句,则正确的描述是,C语言...
  9. VBS隐藏bat窗口
  10. 寻找四叶草HTML5小游戏,寻找四叶草的作文四百字