How Do I separate labels and images?


I am loading a dataset of handwritten images

import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers 

train_data= np.loadtxt('train.txt')
print('train:',train_data.shape)      ##train (7291, 257)

The first digit of each row is a digit from 0-9(labels), and the rest 256 are images. How can I separate these labels from the images? What I am thinking is to make a new tensor with every first digit of each row, and another one with the rest of the digits. Since I am a beginner I am not sure how to do it or if my approach is correct.


You need to learn numpy indexing:

In your case, just do

labels = train_data[:, 0]
images = train_data[:, 1:] 

Answered By – nnzzll

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published