kwo*_*sin 4 python numpy matrix
下面的代码将如何工作?
k = np.array([[ 0., 0.07142857, 0.14285714],
[ 0.21428571, 0.28571429, 0.35714286],
[ 0.42857143, 0.5, 0.57142857],
[ 0.64285714, 0.71428571, 0.78571429],
[ 0.85714286, 0.92857143, 1. ]])
y = np.array([[0, 3, 1, 2],
[2, 1, 0, 3]])
b = k[y]
Run Code Online (Sandbox Code Playgroud)
形状是:
k 形状: (5, 3)
Y 形状:(2, 4)
b 形状:(2,4,3)
为什么 numpy 矩阵接受另一个矩阵作为其索引以及 k 如何找到正确的输出?为什么会产生一个张量呢?
b 的输出为
[[[ 0. 0.07142857 0.14285714]
[ 0.64285714 0.71428571 0.78571429]
[ 0.21428571 0.28571429 0.35714286]
[ 0.42857143 0.5 0.57142857]]
[[ 0.42857143 0.5 0.57142857]
[ 0.21428571 0.28571429 0.35714286]
[ 0. 0.07142857 0.14285714]
[ 0.64285714 0.71428571 0.78571429]]]
Run Code Online (Sandbox Code Playgroud)
这称为整数数组索引。
整数数组索引允许根据 N 维索引选择数组中的任意项目。每个整数数组代表该维度的多个索引。
例子 -
x = array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
rows = np.array([[0, 0],
[3, 3]], dtype=np.intp)
columns = np.array([[0, 2],
[0, 2]], dtype=np.intp)
x[rows, columns]
Run Code Online (Sandbox Code Playgroud)
输出 -
array([[ 0, 2],
[ 9, 11]])
Run Code Online (Sandbox Code Playgroud)
在这种情况下,正如您所看到的,我们通过给出元素的“坐标”来选择角元素。如果你尝试只给出一个二维矩阵,它只会像这样评估它 -
x[rows]
Run Code Online (Sandbox Code Playgroud)
输出 -
array([[[ 0, 1, 2],
[ 0, 1, 2]],
[[ 9, 10, 11],
[ 9, 10, 11]]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8690 次 |
| 最近记录: |