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

I have this subcode in Python and I can't figure out what it is or what it does, especially this statement:

X[:,:,:,i]

Subcode:

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)
+4
source share
1 answer

This is called an array slice. As noted in @ cᴏʟᴅs, it xis a 4D array, and it X[:,:,:,i]receives one specific fragment of a 3D array.

Maybe a smaller example might help.

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

In this case, it matrixis a two-dimensional array:

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

Therefore, it matrix[:, 1]will lead to a smaller fragment matrix:

array([1, 3])

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

, numpy .

+3

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


All Articles