**python中numpy.eye()函数的学习**
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. 函数eye()的作用是返回一个对角线diagonal上全是1,而其他位置全为0的一个二维数组(2D-array)。
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 ——K为对角元素的索引。
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.
默认的索引为0对应的是the main diagonal, index为正值对应一个upper diagonal, index为复制对应的是lower diagonal.
从后续实验结果来看,对角线的形成是以N、M中较小值为标准生成一个方阵的对角线,当索引index取值为3时则该方阵对角线向右移动3个单位,当索引index取值为-2时则该方针对角线向左移动2个单位,详情可以见下面的截图。
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.
New in version 1.14.0.
Returns:
I : ndarray of shape (N,M) ——I为一个N行M列的矩阵,可以指定第K个对角元素处为1.
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.]])