繁体   English   中英

关于python中numpy矩阵的问题

[英]Questions about numpy matrix in python

#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的最终结果是什么?

我们可以使用交互式解释器来找到它。

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.    ]])

我们找回一个matrix对象。 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]给出了所有行和第二列。 换句话说,第2列中的所有元素。

In [21]: hyperplanes[:,2]
Out[21]: 
matrix([[ 1.],
        [ 1.],
        [ 1.],
        [ 1.]])

由于Python是一种解释型语言,因此很容易为自己尝试并找出正在发生的事情。 在将来,如果你遇到困难,请回到翻译,然后尝试一下 - 改变一些数字,取下.T等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM