Python中numpy矩阵的问题

4
#these are defined as [a b]
hyperplanes = np.mat([[0.7071,    0.7071, 1], 
                      [-0.7071,   0.7071, 1],
                      [0.7071,   -0.7071, 1],
                      [-0.7071,  -0.7071, 1]]);

a = hyperplanes[:][:,0:2].T;
b = hyperplanes[:,2];

这些 [:][:,0:2] 的表示是什么意思?a和b的最终结果是什么?
1个回答

8
我们可以使用交互式解释器来找出这个问题的答案。
In [3]: hyperplanes = np.mat([[0.7071,    0.7071, 1], 
   ...:                       [-0.7071,   0.7071, 1],
   ...:                       [0.7071,   -0.7071, 1],
   ...:                       [-0.7071,  -0.7071, 1]])

请注意,在 Python 中,我们不需要在行尾加上分号。
In [4]: hyperplanes
Out[4]: 
matrix([[ 0.7071,  0.7071,  1.    ],
        [-0.7071,  0.7071,  1.    ],
        [ 0.7071, -0.7071,  1.    ],
        [-0.7071, -0.7071,  1.    ]])

我们得到了一个矩阵对象。NumPy通常使用ndarray(你应该使用np.array而不是np.mat),但在这种情况下,无论是矩阵还是ndarray都是相同的。让我们来看看a。
In [7]: hyperplanes[:][:,0:2].T
Out[7]: 
matrix([[ 0.7071, -0.7071,  0.7071, -0.7071],
        [ 0.7071,  0.7071, -0.7071, -0.7071]])

这个切片有点奇怪。请注意:
In [9]: hyperplanes[:]
Out[9]: 
matrix([[ 0.7071,  0.7071,  1.    ],
        [-0.7071,  0.7071,  1.    ],
        [ 0.7071, -0.7071,  1.    ],
        [-0.7071, -0.7071,  1.    ]])

In [20]: np.all(hyperplanes == hyperplanes[:])
Out[20]: True

换句话说,你根本不需要在其中使用[:]。那么,我们只剩下hyperplanes[:,0:2].T[:,0:2]可简化为[:,:2],这意味着我们想要获取hyperplanes中的所有行,但仅限前两列。
In [14]: hyperplanes[:,:2]
Out[14]: 
matrix([[ 0.7071,  0.7071],
        [-0.7071,  0.7071],
        [ 0.7071, -0.7071],
        [-0.7071, -0.7071]])

.T给我们提供转置操作。

In [15]: hyperplanes[:,:2].T
Out[15]: 
matrix([[ 0.7071, -0.7071,  0.7071, -0.7071],
        [ 0.7071,  0.7071, -0.7071, -0.7071]])

最后,b = hyperplanes[:,2]提供了我们需要的所有行及其第二列。换句话说,就是第二列中的所有元素。
In [21]: hyperplanes[:,2]
Out[21]: 
matrix([[ 1.],
        [ 1.],
        [ 1.],
        [ 1.]])

由于Python是一种解释型语言,因此很容易尝试自己的想法并弄清楚发生了什么。如果将来遇到困难,请返回解释器并尝试一些操作--更改一些数字,去掉.T等。


非常感谢您的详细答复。您是正确的,交互式解释器对我来说是最好的学习方式。 - kaleo211

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接