numpy创建单位矩阵和对角矩阵的实例

在学习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 on
  the main diagonal.

  Parameters
  ----------
  n : int
    Number of rows (and columns) in `n` x `n` output.
  dtype : data-type, optional
    Data-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))

>>> A

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

矩阵的运算中还经常使用对角阵,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 : int
   Number of rows in the output.
  M : int, optional
   Number of columns in the output. If None, defaults to `N`.
  k : int, optional
   Index of the diagonal: 0 (the default) refers to the main diagonal,
   a positive value refers to an upper diagonal, and a negative value
   to a lower diagonal.
  dtype : data-type, optional
   Data-type of the returned array.
  order : {'C', 'F'}, optional
    Whether the output should be stored in row-major (C-style) or
    column-major (Fortran-style) order in memory.

    .. versionadded:: 1.14.0

  Returns
  -------
  I : ndarray of shape (N,M)
   An array where all elements are equal to zero, except for the `k`-th
   diagonal, whose values are equal to one.

  See Also
  --------
  identity : (almost) equivalent function
  diag : 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 instance
  a.diagonal(offset=0, axis1=0, axis2=1)

  Return specified diagonals. In NumPy 1.9 the returned array is a
  read-only view instead of a copy as in previous NumPy versions. In
  a 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 is
  returned. The shape of the resulting array can be determined by
  removing `axis1` and `axis2` and appending an index to the right equal
  to 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 resulting
  array 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 to
  the returned array will alter your original array. The returned array
  will have the same type as the input array.

  If you don't write to the array returned by this function, then you can
  just ignore all of the above.

  If you depend on the current behavior, then we suggest copying the
  returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
  of just ``np.diagonal(a)``. This will work with both past and future
  versions of NumPy.

  Parameters
  ----------
  a : array_like
    Array from which the diagonals are taken.
  offset : int, optional
    Offset of the diagonal from the main diagonal. Can be positive or
    negative. Defaults to main diagonal (0).
  axis1 : int, optional
    Axis to be used as the first axis of the 2-D sub-arrays from which
    the diagonals should be taken. Defaults to first axis (0).
  axis2 : int, optional
    Axis to be used as the second axis of the 2-D sub-arrays from
    which the diagonals should be taken. Defaults to second axis (1).

  Returns
  -------
  array_of_diagonals : ndarray
    If `a` is 2-D, then a 1-D array containing the diagonal and of the
    same type as `a` is returned unless `a` is a `matrix`, in which case
    a 1-D array rather than a (2-D) `matrix` is returned in order to
    maintain 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 the
    diagonal.

  Raises
  ------
  ValueError
    If 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)
  >>> a
  array([[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); a
  array([[[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 each
  corresponds to fixing the right-most (column) axis, and that the
  diagonals 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))

>>> A

array([[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创建单位矩阵和对角矩阵的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 详解python中Numpy的属性与创建矩阵

    ndarray.ndim:维度 ndarray.shape:形状 ndarray.size:元素个数 ndarray.dtype:元素数据类型 ndarray.itemsize:字节大小 创建数组: a = np.array([2,23,4]) # list 1d print(a) # [2 23 4] 指定数据类型: a = np.array([2,23,4],dtype=np.int) print(a.dtype) # int 64 dtype可以指定的类型有int32,float,floa

  • python 实现一个反向单位矩阵示例

    反向单位矩阵 单位矩阵即对角线为 1,如下: ​ 那么反向的单位矩阵就是反对角线为 1: ​ 左右镜像操作 这里采用 numpy 实现. 方案 1 import numpy as np A = np.eye(3) print(A) B1 = np.fliplr(A) print(B1) 方案 2 B2 = A[:,::-1] print(B2) 这面这两种方案就可以顺利实现反向单位矩阵的定义了.此外,我们拓展了另外两种操作. 上下镜像操作 方法 1 import numpy as np b =

  • python 实现方阵的对角线遍历示例

    任务描述 对一个方阵矩阵,实现平行于主对角线方向的对角线元素遍历. 从矩阵索引入手: [[ 1 2 3 4 5] [ 6 7 8 9 10] [11 12 13 14 15] [16 17 18 19 20] [21 22 23 24 25]] 上三角的索引遍历: 0 0 1 1 2 2 3 3 4 4 0 1 1 2 2 3 3 4 0 2 1 3 2 4 0 3 1 4 0 4 下三角的索引遍历: 1 0 2 1 3 2 4 3 2 0 3 1 4 2 3 0 4 1 4 0 代码 impo

  • python+numpy实现的基本矩阵操作示例

    本文实例讲述了python+numpy实现的基本矩阵操作.分享给大家供大家参考,具体如下: #! usr/bin/env python # coding: utf-8 # 学习numpy中矩阵的代码笔记 # 2018年05月29日15:43:40 # 参考网站:http://cs231n.github.io/python-numpy-tutorial/ import numpy as np #==================矩阵的创建,增删查改,索引,运算==================

  • numpy使用fromstring创建矩阵的实例

    使用字符串创建矩阵是一个很实用的功能,之前自己尝试了很多次的小功能使用这个方法就能够简单实现. 创建长度为16的字符串,是为了方便能够在各种数据类型之间转换. >>> s = "mytestfromstring" >>> len(s) 16 这个功能其实是比较让我兴奋的一个小功能,因为这个简单的转换实现了ASCII码的转换 >>> np.fromstring(s,dtype=np.int8) array([109, 121, 116

  • numpy 返回函数的上三角矩阵实例

    numpy 返回函数的上三角矩阵 np.triu() matrix2=np.triu(matrix1) numpy.triu(m, k=0)[source] Upper triangle of an array. Return a copy of a matrix with the elements below the k-th diagonal zeroed. np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) array([[ 1, 2, 3]

  • Python numpy.zero() 初始化矩阵实例

    那就废话不多说,直接上代码吧! new_array = np.zeros((107,4))# 共107行 每行4列 初值为0 >>> new_array = np.zeros((107,4)) >>> new_array array([[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., 0., 0.

  • numpy创建单位矩阵和对角矩阵的实例

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

  • NumPy.npy与pandas DataFrame的实例讲解

    用CSV格式来保存文件是个不错的主意,因为大部分程序设计语言和应用程序都能处理这种格式,所以交流起来非常方便.然而这种格式的存储效率不是很高,原因是CSV及其他纯文本格式中含有大量空白符;而后来发明的一些文件格式,如zip.bzip和gzip等,压缩率则有了显著提升. 首先导入模块: In [1]: import numpy as np In [2]: import pandas as pd In [3]: from tempfile import NamedTemporaryFile In [

  • python 创建一维的0向量实例

    第一种方法: A=[0]*8 第二种方法: import numpy as np A=np.zeros(8) 以上这篇python 创建一维的0向量实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • python 申请内存空间,用于创建多维数组的实例

    以三维数组为例 先申请1个一维数组空间: mat = [None]*d1 d1是第一维的长度. 再把mat中每个元素扩展为第二维的长度: for i in range(len(mat)): mat[i][j] = [None]*d2 类似的,把mat中每个元素扩展为第三维的大小: for i in range(len(mat)): for j in range(len(mat[0]): mat[i][j] = [None]*d3 以上是创建的"数组"其实是list类,不是严格意义的数组

  • python numpy生成等差数列、等比数列的实例

    如下所示: import numpy as np # 等差数列 print(np.linspace(0.1, 1, 10, endpoint=True)) print(np.arange(0.1, 1.1, 0.1)) """总结: arange 侧重点在于增量,不管产生多少个数 linspace 侧重于num, 即要产生多少个元素,不在乎增量 """ # 等比数列 np.logspace(1, 4, 4, endpoint=True, base

  • C#动态创建button按钮的方法实例详解

    C#动态创建button按钮的方法实例详解 C#编程中经常需要动态创建,本文主要介绍C#动态创建button按钮的方法,涉及C#按钮属性动态设置的相关技巧,以供借鉴参考.具体实现方法如下: 例子: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.T

  • SpringBoot创建JSP登录页面功能实例代码

    添加JSP配置 1.pom.xml添加jsp解析引擎 <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.s

  • BootStrap创建响应式导航条实例代码

    首先你得引入bootstrap与jquery 推荐一个CDN:http://cdn.gbtags.com/index.html 然后就是开始编写HTML代码.如果你不想更改显示效果的话实际上CSS都免去写了2333 因为HTML代码比较多 这里分为三个部分 然后最后再上一份整体HTML代码 首先如上图所示的,实现这个效果需要了解bootstrap的以下几个组件 •导航条 •按钮 •表单 •下拉菜单 实际上以上几个组件的样式有很多.我们只需要了解一部分即可 如需了解更多的请转自http://www

  • jquery动态创建div与input的实例代码

    无意中发现的,做为收藏,以备后绪查看时用. 实例如下: <html> <head> <title>jjquery动态创建div与input</title> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script> <!--动态创建div--> $(function (){ $(&

  • 创建简单的node服务器实例(分享)

    话不多说直接上代码: var http = require('http') //对URL 解析为对象 //1.导入模块 URl模块 var url = require('url') var fs = require('fs') var path = require('path') var mime = require('./mime.js') var qs = require('querystring') http.createServer(function(req,res){ var url1

随机推荐