Questions about numpy matrix in python

#these are defined as [ab] 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]; 

what do these [:] [:, 0: 2] mean? What are the end results a and b?

+4
source share
1 answer

We can use an interactive interpreter to find out.

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

Note that we do not need semicolons at the end of lines in 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. ]]) 

Return the matrix object. NumPy usually uses ndarray (you would do np.array instead of np.mat above), but in this case everything is the same, whether it be a matrix or ndarray .

Let's look at 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]]) 

Cutting on this is a little strange. Note:

 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 

In other words, you do not need [:] . Then we are left with hyperplanes[:,0:2].T . [:,0:2] can be simplified to [:,:2] , which means that we want to get all the rows in hyperplanes , but only the first two columns.

 In [14]: hyperplanes[:,:2] Out[14]: matrix([[ 0.7071, 0.7071], [-0.7071, 0.7071], [ 0.7071, -0.7071], [-0.7071, -0.7071]]) 

.T gives us transpose.

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

Finally, b = hyperplanes[:,2] gives us all the rows and the second column. In other words, all the items in column 2.

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

Since Python is an interpreted language, it’s easy to try something for yourself and find out what is going on. In the future, if you get stuck, go back to the interpreter and try everything - change some numbers, clear .T , etc.

+8
source

Source: https://habr.com/ru/post/1502938/


All Articles