Why does `X_train[indices.astype(int)]` give a `TypeError`?

It looks like you’re getting a TypeError when trying to use the indices array in X_train[indices.astype(int)]. This error can occur if indices is not a 1D array of integers as expected.

One thing to check is the shape of indices using indices.shape. It should be (50000,), indicating a 1D array with 50000 elements.

If the shape is correct, you can try converting indices to a list before indexing:

out_images = [X_train[i] for i in indices.astype(int)]

This list comprehension should extract the elements from X_train corresponding to the indices in indices.

Hey Archana,

Interesting doubt, here is the Answer to the Question:-

The error message indicates that X_train is a list, not a NumPy array, which doesn’t support array indexing. To fix this, convert X_train to a NumPy array before indexing:

out_images = np.array(X_train)[indices.astype(int)]

This converts X_train to a NumPy array and then indexes it using the integer indices from indices.astype(int).

Hey Archna,

Use list comprehension to select elements from X_train based on the indices:

This iterates over the indices array and selects the corresponding elements from X_train, creating a new list out_images.

out_images = [X_train[i] for i in indices.astype(int)]

Hey Archana,

Convert X_train to a NumPy array before indexing:

This first converts X_train to a NumPy array X_train_np, then indexes it using the integer indices from indices.astype(int) to get out_images.

X_train_np = np.array(X_train) out_images = X_train_np[indices.astype(int)]