numpy.eye使用方法

https://docs.scipy.org/doc/numpy/reference/generated/numpy.eye.html

https://www.numpy.org.cn/article/basics/different_ways_create_numpy_arrays.html#%E4%BD%BF%E7%94%A8%E5%85%B6%E4%BB%96Numpy%E5%87%BD%E6%95%B0

https://www.programcreek.com/python/example/6118/numpy.eye

对角矩阵

Return a 2-D array with ones on the diagonal and zeros elsewhere.

返回一个 对角线是1,其余是0的 2维数组。

参数

  • N (行)
  • M (列)
  • 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)
  • dtype 数据类型
  • order (Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory)

例子

N+dtype

1
2
3
4
5
import numpy as np
np.eye(2, dtype=int)

#array([[1, 0],
# [0, 1]])
1
2
3
4
5
np.eye(3, dtype=int)

#array([[1, 0, 0],
# [0, 1, 0],
# [0, 0, 1]])
1
2
3
4
5
6
np.eye(4, dtype=int)

#array([[1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 1, 0],
# [0, 0, 0, 1]])

N+M

1
2
3
4
np.eye(2, 2)

#array([[1., 0.],
# [0., 1.]])
1
2
3
4
5
np.eye(3, 6)

#array([[1., 0., 0., 0., 0., 0.],
# [0., 1., 0., 0., 0., 0.],
# [0., 0., 1., 0., 0., 0.]])

N+K

1
2
3
4
5
np.eye(3, k=1)

#array([[0., 1., 0.],
# [0., 0., 1.],
# [0., 0., 0.]])
1
2
3
4
5
6
np.eye(4, k=1)

#array([[0., 1., 0., 0.],
# [0., 0., 1., 0.],
# [0., 0., 0., 1.],
# [0., 0., 0., 0.]])