Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of X[:,:,:,i] in numpy?

Tags:

python

numpy

I have this subcode in Python and I cannot understand what it is or what it does, especially this statement:

X[:,:,:,i]

The subcode is:

train_dict = sio.loadmat(train_location)
X = np.asarray(train_dict['X'])

X_train = []
for i in range(X.shape[3]):
    X_train.append(X[:,:,:,i])
X_train = np.asarray(X_train)

Y_train = train_dict['y']
for i in range(len(Y_train)):
    if Y_train[i]%10 == 0:
        Y_train[i] = 0
Y_train = to_categorical(Y_train,10)
return (X_train,Y_train)
like image 697
AAA Avatar asked Jul 18 '17 13:07

AAA


People also ask

What does X [: I mean in Python?

Meaning of X = X[:, 1] in Python is: X is a dataset or a array. Say Here X have n rows and n columns. so by doing x=x[:,1] we get all the rows in x present at index 1.

What does this mean in Python [: 0?

edited Nov 27, 2020 by hari_sh. It acts as an indicator in the format method that if you want it to be replaced by the first parameter(index zero) of format. Example : print(42+261={0}.format(303)) Here, {0} will be replaced by 303.

What does X mean in Python?

X is a variable name, so could be any name allowed by python for variable names. As a variable , it's value will be different every time the loop circle ends, in this particular loop range(10) the value of x will start in 0 and next 1 , and next 2, until reach value of 10.

What is Axis in NP mean?

NumPy axes are the directions along the rows and columns. Just like coordinate systems, NumPy arrays also have axes. In a 2-dimensional NumPy array, the axes are the directions along the rows and columns.


1 Answers

This is called array slicing. As @cᴏʟᴅsᴘᴇᴇᴅ mentioned, x is a 4D array and X[:,:,:,i] gets one specific 3D array slice of it.

Maybe an example with fewer dimensions can help.

matrix = np.arange(4).reshape((2,2))

In this case matrix is a bidimensional array:

array([[0, 1],
       [2, 3]])

Therefore matrix[:, 1] will result in a smaller slice of matrix:

array([1, 3])

In original code matrix[:,:,:, 1] each of the first : mean something like "all elements in this dimension".

Have a look at how array slicing works in numpy here.

like image 139
Bonifacio2 Avatar answered Sep 27 '22 20:09

Bonifacio2