how to convert numpy to tfrecords and then generate batches?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
A typical TensorFlow input pipeline has two separate jobs: serialize raw examples into TFRecord files, then parse those records back into tensors and batch them efficiently. If you keep those steps distinct, the pipeline becomes easier to debug and scale.
Decide What One Example Looks Like
Before writing TFRecords, define the structure of a single example clearly. Suppose each sample has:
- a feature vector of floats
- one integer label
NumPy setup:
Each row in x will become one TFRecord example.
Write NumPy Data to TFRecords
TensorFlow stores structured examples as serialized protocol buffers. A common pattern is to convert each NumPy row into a tf.train.Example.
That creates a TFRecord file where each record is one serialized example.
Parse Records Back into Tensors
Reading TFRecords is the mirror image of writing them. You define a schema and parse each serialized record.
The shape [3] matches the length of each feature vector that was written earlier.
Generate Batches with tf.data
Now build the input pipeline.
This is the standard modern TensorFlow approach. map, batch, and prefetch are the core pieces.
Variable-Length Data Needs a Different Schema
If your NumPy data does not have a fixed shape, you usually serialize the array as raw bytes or use variable-length features instead of FixedLenFeature.
For fixed-size tabular data, FixedLenFeature is the simplest and fastest choice. Do not make the schema more complicated than the data requires.
Separate Train, Validation, and Test Files
A practical project usually writes separate TFRecord files for different data splits.
That keeps your pipeline explicit and avoids mixing split logic into runtime data loading.
Why Use TFRecords at All
TFRecords are helpful when:
- the dataset is large
- training reads many examples repeatedly
- you want a stable binary format for TensorFlow pipelines
- preprocessing should happen once, not every epoch from raw text or CSV
For very small datasets, plain NumPy arrays or in-memory tensors may be simpler. TFRecords become more valuable as scale and pipeline complexity increase.
Common Pitfalls
The biggest mistake is writing one schema and parsing with another. If the field name, dtype, or shape changes between the write and read step, parsing will fail.
Another mistake is storing everything as strings or bytes when fixed-size numeric features would be simpler and faster.
Developers also sometimes forget that batching happens after parsing. The parser should describe one example, not the entire batch.
Finally, do not skip verification. After writing TFRecords, always read a few examples back and confirm the tensors look correct before starting model training.
Summary
- Write TFRecords by serializing one example at a time with
tf.train.Example. - Parse them with a matching schema using
tf.io.parse_single_example. - Build batches with
tf.data.TFRecordDataset,map,batch, andprefetch. - Keep the record schema aligned exactly between the write and read steps.
- Use TFRecords when dataset size and training repetition justify a binary input pipeline.

