Split tensor into training and test sets
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Splitting a tensor into training and test sets is not just slicing at some index. In machine learning, the important part is keeping related tensors aligned, usually shuffling first, and making sure the split is reproducible when experiments need to be compared.
Split by Shuffled Indices
If your features and labels are already in memory as tensors, a reliable pattern is to shuffle indices once and then use tf.gather.
This is a strong default because the same index split is applied to both tensors, so feature-label alignment is preserved.
Avoid Splitting Features and Labels Separately
A common mistake is to shuffle or split features and labels independently. That destroys the correspondence between each training example and its label.
The correct mental model is that the dataset is split by example index, not by tensor value. Once you have the index sets, gather every related tensor with those same indices.
Make the Split Reproducible
If you need repeatable experiments, use a fixed random seed.
Without a seed, each run may produce a different split. That is often fine in production training pipelines, but it makes debugging and comparison harder.
tf.data.Dataset Can Also Split Cleanly
If you are already using tf.data, you can shuffle once and then use take and skip.
This style is useful when the next steps are batching, mapping, caching, and prefetching anyway.
Stratification Is a Separate Concern
Random splitting is fine for many tasks, but some classification problems need class balance preserved between train and test sets. TensorFlow tensors alone do not automatically give you stratified splitting.
If class balance matters, you either build the stratified index logic yourself or split with a utility designed for that job before converting back to tensors. The important point is that stratification is an extra requirement, not something ordinary random slicing provides.
Watch the Axis You Are Splitting
In most supervised learning datasets, the first axis is the sample axis. That is the axis you split.
If the tensor shape is [batch, height, width, channels], the split is along the batch dimension, not across the image width or height. This sounds obvious, but shape mistakes are common when people move from simple vectors to multidimensional tensors.
Common Pitfalls
- Splitting features and labels separately and breaking their alignment.
- Slicing without shuffling when the original tensor order has structure or bias.
- Forgetting to set a seed when reproducibility matters.
- Assuming random splitting automatically preserves class balance.
- Splitting along the wrong axis in multidimensional tensors.
Summary
- Split datasets by shuffled example indices, not by separate tensor operations on each field.
- Use
tf.gatherwhen working directly with in-memory tensors. - Use
tf.data.Dataset.shuffle,take, andskipwhen the pipeline is already dataset-based. - Keep reproducibility in mind by setting a seed when needed.
- Treat stratification as a separate requirement from ordinary train-test splitting.
Related reading
- Split .tfrecords file into many .tfrecords files
- Split train data to train and validation by using tensorflow_datasets.load TF 2.1
- Splitting a tensorflow dataset into training, test, and validation sets from keras.preprocessing API
- Spring Boot embedded HornetQ cluster not forwarding messages
- Split vector into balanced list balancing sum of list elements
- Splitting a list into N parts of approximately equal length
- squad2.0 training error THCudaCheck FAIL file/pytorch/aten/src/THC/THCGeneral.cpp line50 error100 no CUDA-capable device is detected
- SSD anchors in Tensorflow detection API

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.