精华内容
下载资源
问答
  • 在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础。numpy中创建单位矩阵借助identity...单位数组的概念与单位矩阵相同,主对角线元素为1,其他元素均为...

    在学习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=, 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创建单位矩阵和对角矩阵的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

    展开全文
  • 今天小编就为大家分享一篇numpy创建单位矩阵和对角矩阵的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • numpy创建单位矩阵和对角矩阵

    万次阅读 2019-05-09 22:50:00
    在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础。 numpy中创建单位矩阵借助identity...单位数组的概念与单位矩阵相同,主对角线元素为1,其他元素均...

    在学习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])
    
    展开全文
  • 在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础。numpy中创建单位矩阵借助identity...单位数组的概念与单位矩阵相同,主对角线元素为1,其他元素均为...

    在学习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=, 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创建单位矩阵和对角矩阵的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

    展开全文
  • 在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础。numpy中创建单位矩阵借助identity...单位数组的概念与单位矩阵相同,主对角线元素为1,其他元素均为...

    在学习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=, 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创建单位矩阵和对角矩阵的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

    展开全文
  • 在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础。numpy中创建单位矩阵借助identity...单位数组的概念与单位矩阵相同,主对角线元素为1,其他元素均为...
  • 对角矩阵

    千次阅读 2018-03-26 11:18:58
    对角矩阵(diagonal matrix)是一个主对角线之外的元素皆为0的矩阵,常写...对角线上元素全为1的对角矩阵称为单位矩阵对角矩阵的运算包括、差运算、数乘运算、同阶对角阵的乘积运算,且结果仍为对角阵。定义 (1...
  • 一般矩阵的相似对角化用它的特征向量组成的矩阵就可以了,为什么实对称矩阵的相似对角化这么特殊呢,名称叫做正交矩阵化,求得特征向量矩阵后还要正交化和单位化使之成为正交矩阵呢? 答: 对称矩阵也可以用一般的由...
  • (这两个最不特殊了,线代中学过不过有点忘)1、对角矩阵对角矩阵(diagonal matrix)是一个主对角线之外的元素皆为0的矩阵,常...对角线上元素全为1的对角矩阵称为单位矩阵对角矩阵的运算包括、差运算、数乘...
  • 在讨论今天的主题之前...可逆矩阵:存在n阶矩阵An阶矩阵B,使得矩阵A、B的乘积为单位矩阵,则称A为可逆矩阵,B为A的逆矩阵。对角矩阵:一个主对角线之外的元素都为0的矩阵。根据我的主题,大家也能够想到今天要谈...
  • 单位矩阵和逆矩阵

    千次阅读 2018-11-20 16:13:00
     任意向量和单位矩阵相乘,都不会改变  我们将保持 n 维向量不变的单位矩阵记作 I n ,形式上,I n ∈ R n×n 2.矩阵的逆   矩阵 A 的矩阵逆(matrix inversion)记作 A −1 ,其定义的矩阵满足如下条件 ...
  • 2.1 特殊矩阵2.1.1 通用性的特殊矩阵zeros 函数:产生全 0 矩阵,即零矩阵ones 函数:产生全 1 矩阵,即幺矩阵eye 函数:产生对角线为 1 的矩阵,当矩阵为方阵时,得到一个单位矩阵rand 函数:产生(0,1)区间均匀...
  • 矩阵A和矩阵B的矩阵乘积是第三个矩阵C 若A为mxn,B为nxp,则C为mxp。...单位矩阵In:所有沿对角线的元素都是1,而其他位置的元素都是0 矩阵A的逆矩阵:A-1 矩阵和逆矩阵满足:A-1A=In 转载于:https...
  • 正交矩阵的充要条件正交操作对称矩阵的定义对称矩阵的正交化矩阵P和对角矩阵D的求解方法对称矩阵对角化的好处1、正交矩阵定义矩阵的列相互正交独立矩阵的列的长度为12、正交矩阵的性质正交矩阵与它的转置的乘积为...
  • 最后的结论就是:如果不做正交单位话,我们一样可以通过U(把特征向量按照列写成的矩阵),把一个实对称矩阵对角化为以它的特征值为对角元的对角矩阵。 我们知道,对应一个特征值的特征向量乘以任何一个非零
  • 单位矩阵

    2020-02-19 11:56:19
    单位矩阵是指主对角线上元素全部为1,其余元素全部为0的方阵。主对角线是指左上角到右下角方向的对角线。数据规模(1<=M,N<=1000)。 Input 多组数据输入,每组第一行输入MN,空格分开,接下来M行输入矩阵...
  • 单位矩阵题解

    2020-06-16 21:24:51
    单位矩阵是指主对角线上元素全部为1,其余元素全部为0的方阵。主对角线是指左上角到右下角方向的对角线。数据规模(1<=M,N<=1000)。 输入格式 多组数据输入,每组第一行输入MN,空格分开,接下来M行输入矩阵...
  • 单位矩阵就是一个正方形矩阵,它除了主对角线元素值为1以外,其余元素的值均为0,例如: *1 0 0 *0 1 0 *0 0 1 *就是一个3×3单位矩阵,编写一个名叫identity_matrix的函数,它接受一个10×10整型矩阵为参数 *成功...
  • 矩阵

    2019-11-08 17:19:52
    对角矩阵是方阵矩阵,单位矩阵对角矩阵 n×1矩阵,列向量 1×n 矩阵, 行向量 矩阵的转置,沿着对角线翻折,行变成列,列变成行 行向量的转置是列向量,列向量的转置是行向量 对角矩阵的转置等于本身 的转置= ...
  • 即在单位矩阵中,主对角线都为1。 ==> 单位矩阵一定是方阵。 单位矩阵的性质 I . A = A 通过矩阵乘法定义 ==> 也满足 A . I = A 同理 ==> 矩阵的逆 在数字系统中: X . (X)的负一次方 = 1,0是没
  • 看过下文大致可以知道,PCA本质是对角化协方差矩阵,目的是让维度之间的相关性最小(降噪),保留下来的维度能量最大(去冗余),PCA在图像数据的降维上很实用,因为图像数据相邻元素的相关性是很高的。 为了方便...
  • % eys函数 :产生对角线为1的矩阵。当矩阵是方阵时,得到一个单位矩阵 % rand函数:产生(0,1)区间均匀分布的随机矩阵 % randn函数: 产生均值为0,方差为1的标准正态分布随机矩阵 %调用方式 % zeros函数的调用...

空空如也

空空如也

1 2 3 4 5 ... 16
收藏数 314
精华内容 125
关键字:

对角矩阵和单位矩阵