tensorflow constant with variable size
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
TensorFlow constants are immutable tensors, so their values do not change after creation. A common question is whether a constant can have variable size. The short answer is that the created constant has a fixed value and shape, but you can build functions that produce tensors whose shape depends on runtime input.
What tf.constant Does and Does Not Do
tf.constant materializes a concrete tensor immediately.
The shape here is fixed as length three. You cannot resize c in place because constants are immutable.
If you need different sizes, create a new tensor for each size:
This works in eager mode because Python constructs a new list before TensorFlow creates the constant.
Build Runtime-Dependent Tensors with Tensor Ops
In graph workflows, Python list construction is not enough for dynamic dimensions. Instead, use TensorFlow ops that accept dynamic shape tensors.
tf.fill produces new tensors with runtime-defined size, while each produced tensor is still immutable after creation.
For two-dimensional shapes:
This pattern is often what people mean by a constant with variable size.
Use tf.Variable for Mutable State
If the requirement is to update stored values over time, use tf.Variable instead of constants.
Variables are mutable and optimized for training state such as weights and moving averages.
If shape changes are required, declare flexible shape behavior carefully.
Even then, shape flexibility has constraints and should be used intentionally.
Handle Irregular Length Data with RaggedTensor
For batches containing sequences of different lengths, RaggedTensor is often cleaner than forcing padded constants.
Ragged tensors represent variable-length rows directly and are useful in NLP and recommendation pipelines.
Shape Signatures in tf.function
When tracing functions, shape signatures help TensorFlow compile reusable graphs.
The None dimension allows varying input length while preserving a consistent function contract.
Dynamic Batching with Padding
For sequence tasks, per-example lengths vary while batch tensors need rectangular shapes. Use padded batching to keep runtime flexibility.
This keeps source examples variable in length while producing tensors suitable for model input.
Common Pitfalls
A common misunderstanding is expecting tf.constant itself to resize after creation. It never mutates, so shape changes always mean creating a new tensor.
Another issue is mixing Python-side dynamic list creation with tf.function tracing and expecting graph-level flexibility automatically. Use TensorFlow shape-aware ops for robust graph behavior.
Developers also overuse tf.Variable when immutable tensors are enough. Mutable state adds complexity and should be limited to parameters or counters that truly need updates.
Summary
tf.constantcreates immutable tensors with fixed value and shape.- Variable-size results come from creating new tensors, often via dynamic TensorFlow ops.
- Use
tf.fill,tf.ones, or related ops for runtime-dependent shapes in graphs. - Use
tf.Variableonly when data must be updated over time. - Consider
RaggedTensorandTensorSpecfor variable-length workflows.
Related reading
- Tensorflow conv2d_transpose Size of out_backprop doesn't match computed
- Tensorflow Convolution Neural Network with different sized images
- Tensorflow Convolutions with different filter for each sample in the mini-batch
- Tensorflow Could not load dynamic library 'libcudart.so.10.0 on ubuntu 18.04
- Tensorflow Convert pb file to TFLITE using python
- Tensorflow. Converting unknown dimension size of a tensor to int
- ''tensorflow_core.estimator'' has no attribute ''inputs'', why does this happen?
- TensorFlow Correct way of excluding one class from loss function
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free 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.