我们可以使用交互式解释器来找出这个问题的答案。
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
等。