TensorFlow Tutorial for Deep Learning in Python — Part 2: Tensors: Shapes, Data Types and Operations
Everything TensorFlow works with is a tensor: a grid of numbers with a shape and a data type. In this part you build tensors by hand, turn a flower photo into a tensor of 138,240 numbers, scale it, slice it, turn it gray with a single matrix multiplication, and resize five photos of different sizes into the one batch a model can learn from.
This is Part 2 of a 19-part series.
- Part 1: Install TensorFlow and Set Up Your First Project
- Part 2: Tensors: Shapes, Data Types and Operations (you are here)
- Part 3: Variables and Automatic Differentiation with GradientTape (coming soon)
- Part 4: Build an Image Input Pipeline with tf.data (coming soon)
- Part 5: Build Your First Neural Network with Keras (coming soon)
- Part 6: Build a Convolutional Neural Network (coming soon)
- Part 7: Monitor Training with Callbacks and TensorBoard (coming soon)
- Part 8: Reduce Overfitting with Data Augmentation and Dropout (coming soon)
- Part 9: Transfer Learning and Fine-Tuning with a Pretrained Model (coming soon)
- Part 10: Evaluate a Classifier: Confusion Matrix, Precision and Recall (coming soon)
- Part 11: Save, Load and Export a Keras Model (coming soon)
- Part 12: Text Classification with TextVectorization (coming soon)
- Part 13: Word Embeddings and LSTM Networks for Text (coming soon)
- Part 14: Time Series Forecasting: Windows, Normalization and Baselines (coming soon)
- Part 15: Forecast with LSTM and Conv1D Models (coming soon)
- Part 16: Write a Custom Training Loop with tf.function (coming soon)
- Part 17: Convert a Keras Model to LiteRT (coming soon)
- Part 18: Serve TensorFlow Models with FastAPI (coming soon)
- Part 19: Production Checklist and Recap (coming soon)
Every command and output on this page is real, captured while building the project.
What a Tensor Is
TensorFlow's guide to tensors defines them in one line: "Tensors are multi-dimensional arrays with a uniform type (called a dtype)." In plainer words, a tensor is a grid of numbers that are all of the same kind. A single number is a tensor, and so are a list of numbers, a table, and a photo. Four words describe every tensor, and you'll use them all through the series:
| Word | What it means | For a colour photo 192 pixels high and 240 wide |
|---|---|---|
| Shape | How many items lie along each axis | (192, 240, 3): 192 rows, 240 pixels in each row, 3 colours in each pixel |
| Rank | How many axes it has | 3 |
| Size | How many numbers it holds: the numbers of its shape multiplied together | 192 × 240 × 3 = 138,240 |
Data type (dtype) | The kind of number every item is | uint8: a whole number from 0 to 255 |
An axis is one direction you can count along: a list has one, a table two (its rows and its columns), and a colour photo three. The guide adds a rule that shapes how you work with tensors: "All tensors are immutable like Python numbers and strings: you can never update the contents of a tensor, only create a new one." Every operation in this part gives you a new tensor and leaves the old one as it was.
What This Part Builds
The image classifier from Part 1 has 3,670 flower photos in data/flowers/flower_photos. A model can't read a JPEG file: it needs every photo as a tensor of numbers, and every photo in a batch the same shape. This is the journey from a file to a batch, which this part takes one step at a time:
Steps 1 to 6 teach tensors on small practice scripts. Step 7 adds the project's own code for it, src/image_classifier/photos.py, with a load_photo function that takes a photo through the first three arrows.
Versions Used
| Tool | Version |
|---|---|
| Python | 3.14.10 |
| uv | 0.13.10 |
| TensorFlow | 2.22.0 |
| NumPy | 2.5.5 |
| Git | 2.56.1 |
They're the same as in Part 1. The outputs were captured on a Mac with an Apple M1 Pro, on its CPU. Every command in this part works unchanged in PowerShell on Windows.
What This Part Costs
Nothing. Everything runs on your own computer, and the practice scripts and the images they save take about 140 KB.
Prerequisites
- The project from Part 1: Install TensorFlow and Set Up Your First Project, with the flower photos downloaded. Every command in this part runs in its folder,
dewiride-image-classifier.
Step 1: Create Your First Tensors
The scripts in Steps 1 to 6 are practice: they show what tensors do, and they aren't part of the app. Keep them in a folder of their own. In the project folder, create it:
mkdir scratch
mkdir makes a folder, and prints nothing. Keep the folder out of Git: at the end of .gitignore, add a blank line and then these two lines:
# Practice scripts from the tutorial, not part of the app
scratch/
Now create scratch/first_tensors.py:
import tensorflow as tf
number = tf.constant(7)
numbers = tf.constant([0.5, 1.5, 2.5])
table = tf.constant([[1, 2, 3], [4, 5, 6]])
print(number)
print(numbers)
print(table)
tf.constant makes a tensor from a Python value: here a number, a list, and a list of two lists. Run the script from the project folder:
uv run python scratch/first_tensors.py
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor([0.5 1.5 2.5], shape=(3,), dtype=float32)
tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)

Each tensor prints as tf.Tensor(, then its values, its shape and its data type:
numberhas the shape(), which is empty: a single number has no axes. Its type isint32, a 32-bit whole number, which is what TensorFlow makes of whole numbers unless you ask for another type.numbershas the shape(3,): one axis, with three items. The comma is how Python writes a tuple with one item. Decimals becomefloat32, 32-bit decimal numbers.tablehas the shape(2, 3): two rows of three. The first number in a shape counts along the first axis, here the rows.
The guide calls these a scalar, of rank 0, a vector, of rank 1, and a matrix, of rank 2. How to Create a Tensor in TensorFlow with tf.constant shows how to choose a tensor's data type yourself.
Step 2: Read a Tensor's Shape, Rank and Size
A colour photo is a grid of pixels, and each pixel is three numbers: how much red, green and blue it has, each from 0 to 255. Here's a photo you can type, 2 pixels high and 4 wide. Create scratch/tiny_photo.py:
import tensorflow as tf
# A photo 2 pixels high and 4 pixels wide. Each pixel is [red, green, blue].
tiny_photo = tf.constant(
[
[[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0]],
[[0, 0, 0], [85, 85, 85], [170, 170, 170], [255, 255, 255]],
]
)
print("Shape:", tiny_photo.shape)
print("Rank: ", tiny_photo.ndim)
print("Size: ", tf.size(tiny_photo).numpy())
print("Type: ", tiny_photo.dtype)
print(tiny_photo.numpy())
The top row is red, green, blue and yellow, which is red and green together. The bottom row goes from black, through two greys, to white: a pixel is grey when its three numbers are equal. The script prints the tensor's shape with .shape, its rank with .ndim, its size with tf.size and its data type with .dtype. Run it:
uv run python scratch/tiny_photo.py
Shape: (2, 4, 3)
Rank: 3
Size: 24
Type: <dtype: 'int32'>
[[[255 0 0]
[ 0 255 0]
[ 0 0 255]
[255 255 0]]
[[ 0 0 0]
[ 85 85 85]
[170 170 170]
[255 255 255]]]

- Shape
(2, 4, 3): 2 rows, 4 pixels in each row, 3 numbers in each pixel. The first axis is the photo's height, the second its width, and the third its colour channels: red, green and blue. Every photo in this series keeps its axes in that order. - Rank 3: three axes.
ndimis short for "number of dimensions", NumPy's word for axes. - Size 24: 2 × 4 × 3 numbers.
tf.sizereturns a tensor too, and.numpy()turns it into a plain number. How to Count the Elements of a Tensor in TensorFlow with tf.size shows it on its own. - Type
int32: the numbers were typed as whole numbers.
The last line prints tiny_photo.numpy(): the values alone, as a NumPy array, without the tf.Tensor( around them. How to Convert a TensorFlow Tensor to a NumPy Array with numpy() shows where .numpy() doesn't work.
Step 3: Choose the Right Data Type
tiny_photo is int32, so each of its numbers takes 4 bytes, though a colour value never goes past 255. Photos use a smaller type, and models a different one. Create scratch/data_types.py:
import tensorflow as tf
print("uint8 holds", tf.uint8.min, "to", tf.uint8.max, "in", tf.uint8.size, "byte")
print("float32 uses", tf.float32.size, "bytes")
pixels = tf.constant([0, 128, 255], dtype=tf.uint8)
print(pixels)
print(pixels + 50)
as_floats = tf.cast(pixels, tf.float32)
print(as_floats + 50)
tf.uint8 and tf.float32 are data types, and each knows its smallest value, .min, its largest, .max, and its size in bytes, .size. dtype=tf.uint8 makes pixels a uint8 tensor, and the script adds 50 to it. Run it:
uv run python scratch/data_types.py
uint8 holds 0 to 255 in 1 byte
float32 uses 4 bytes
tf.Tensor([ 0 128 255], shape=(3,), dtype=uint8)
tf.Tensor([ 50 178 49], shape=(3,), dtype=uint8)
tf.Tensor([ 50. 178. 305.], shape=(3,), dtype=float32)

uint8is an unsigned 8-bit integer: a whole number from 0 to 255, in 1 byte. A JPEG photo decodes touint8, one byte for each colour value. How to Find the Smallest and Largest Value a TensorFlow Data Type Can Hold shows.min,.maxand.sizefor other types.float32is a 32-bit decimal number, in 4 bytes. Neural networks do their maths in it.- The surprise:
pixels + 50turned 255 into 49, with no error. The sum staysuint8, which can't hold 305, so it wrapped around past 255 and started again from 0: 305 − 256 = 49. A pixel that should have got brighter turned almost black. Fixed: 255 + 50 Gives 49 for a uint8 Tensor in TensorFlow shows why, and how to keep such sums at 255. - The way round it:
tf.cast(pixels, tf.float32)makes afloat32copy, where 255 + 50 is 305. How to Change a Tensor's Data Type in TensorFlow with tf.cast coverstf.cast.
That gives the rule for the rest of the series: photos arrive as uint8, and you convert them to float32 before doing maths on them.
Step 4: Turn a Photo into a Tensor
Now a real photo: the tulip from Part 1's grid of flowers, tulips/4042180234_64cd2859c9_m.jpg. Create scratch/photo_tensor.py:
import tensorflow as tf
path = "data/flowers/flower_photos/tulips/4042180234_64cd2859c9_m.jpg"
data = tf.io.read_file(path)
print("File: ", data.shape, data.dtype)
photo = tf.io.decode_jpeg(data, channels=3)
print("Photo:", photo.shape, photo.dtype)
print("Top-left pixel:", photo[0, 0].numpy())
print("Red channel: ", photo[:, :, 0].shape)
print("Top half: ", photo[:96].shape)
print("Values from", tf.reduce_min(photo).numpy(), "to", tf.reduce_max(photo).numpy())
print("Mean of each channel:", tf.reduce_mean(photo, axis=[0, 1]).numpy())
tf.io.read_file(path)reads the file into a tensor: a single string, holding the JPEG file's bytes. TensorFlow doesn't know yet that it's a photo. How to Read a File into a Tensor in TensorFlow with tf.io.read_file shows it on a text file.tf.io.decode_jpeg(data, channels=3)turns those bytes into pixels. Its API page says it decodes "a JPEG-encoded image to a uint8 tensor", andchannels=3asks it to "output an RGB image", with three colours for every pixel. How to Read a JPEG Image into a Tensor in TensorFlow with decode_jpeg shows both steps on a painting from TensorFlow's example images.photo[0, 0]picks one pixel: row 0, column 0, the top-left one. Counting starts at 0, as in a Python list.photo[:, :, 0]keeps every row (:), every column (:), and only channel 0, the red one.photo[:96]keeps the first 96 rows: the top half. How to Index and Slice a Tensor in TensorFlow shows more ways to pick parts of a tensor.tf.reduce_minandtf.reduce_maxfind the smallest and the largest number in the whole tensor. "Reduce" means the result has fewer axes than the input: here, none. How to Find the Smallest Value in a Tensor with tf.reduce_min and How to Find the Largest Value in a Tensor with tf.reduce_max show both.tf.reduce_mean(photo, axis=[0, 1])averages along axes 0 and 1, the rows and the columns, and keeps axis 2: one average for each colour. How to Calculate the Average of a Tensor with tf.reduce_mean explainsaxis.
Run it:
uv run python scratch/photo_tensor.py
File: () <dtype: 'string'>
Photo: (192, 240, 3) <dtype: 'uint8'>
Top-left pixel: [102 88 87]
Red channel: (192, 240)
Top half: (96, 240, 3)
Values from 0 to 255
Mean of each channel: [138 74 34]

The file is one string, of shape (). The photo is 192 pixels high and 240 wide: a uint8 tensor of shape (192, 240, 3), whose values use the whole range from 0 to 255. Its top-left pixel, in the photo's blurred background, is [102 88 87]: a dark grey with a little more red than green or blue. Two shapes show a rule worth knowing:
- The red channel lost an axis:
(192, 240). Picking one item with a single number,0, removes that axis. The guide puts it as "Indexing with a scalar removes the axis". - The top half kept all three:
(96, 240, 3). A slice such as:96keeps its axis, with fewer items on it: "Indexing with a : slice keeps the axis".
The last line looks wrong. [138 74 34] are whole numbers, and an average of 46,080 pixels is hardly ever a whole number. The tf.math.reduce_mean API page explains it: "tf.reduce_mean has an aggressive type inference from input_tensor". The average of a uint8 tensor is a uint8 too, so the fraction was dropped. Fixed: tf.reduce_mean Returns a Whole Number for an Integer Tensor shows the problem on a small example. Step 3's rule fixes it: convert to float32 first. Change the last line to:
print("Mean of each channel:", tf.reduce_mean(tf.cast(photo, tf.float32), axis=[0, 1]).numpy())
Run it again:
uv run python scratch/photo_tensor.py
File: () <dtype: 'string'>
Photo: (192, 240, 3) <dtype: 'uint8'>
Top-left pixel: [102 88 87]
Red channel: (192, 240)
Top half: (96, 240, 3)
Values from 0 to 255
Mean of each channel: [138.42413 74.13952 34.079556]

Now the averages keep their decimals: 138.42 for red, 74.14 for green and 34.08 for blue. Red is by far the strongest colour in this photo of red and yellow tulips, and blue the weakest.
Step 5: Scale the Pixels from 0–255 to 0–1
Models learn better from small numbers. TensorFlow's Load and preprocess images tutorial, which uses these same flower photos, says: "The RGB channel values are in the [0, 255] range. This is not ideal for a neural network; in general you should seek to make your input values small." Dividing every value by 255 puts it between 0 and 1. Create scratch/scale.py:
import tensorflow as tf
path = "data/flowers/flower_photos/tulips/4042180234_64cd2859c9_m.jpg"
photo = tf.io.decode_jpeg(tf.io.read_file(path), channels=3)
scaled = photo / 255.0
print("Scaled:", scaled.shape, scaled.dtype)
print("Values from", tf.reduce_min(scaled).numpy(), "to", tf.reduce_max(scaled).numpy())
Run it:
uv run python scratch/scale.py
Traceback (most recent call last):
File "/Users/you/source/dewiride-image-classifier/scratch/scale.py", line 6, in <module>
scaled = photo / 255.0
~~~~~~^~~~~~~
File "/Users/you/source/dewiride-image-classifier/.venv/lib/python3.14/site-packages/tensorflow/python/util/traceback_utils.py", line 167, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/Users/you/source/dewiride-image-classifier/.venv/lib/python3.14/site-packages/tensorflow/python/ops/math_ops.py", line 1505, in _truediv_python3
raise TypeError(f"`x` and `y` must have the same dtype, "
f"got {x_dtype!r} != {y_dtype!r}.")
TypeError: `x` and `y` must have the same dtype, got tf.uint8 != tf.float32.

The division on line 6 stopped, and the error names both types: tf.uint8 != tf.float32. The traceback ends in _truediv_python3, the function behind /, in TensorFlow's math_ops.py. That function tries to turn 255.0 into the photo's type, uint8. A uint8 can't hold a decimal, so 255.0 became a float32 instead, and a division needs both of its sides to have the same type. Fixed: TypeError: x and y must have the same dtype, got tf.uint8 != tf.float32 follows the error through TensorFlow's code.
The fix is Step 3's rule again: convert the photo to float32, then divide. Replace the file with this version, which also adds four lines that use a feature called broadcasting:
import tensorflow as tf
path = "data/flowers/flower_photos/tulips/4042180234_64cd2859c9_m.jpg"
photo = tf.io.decode_jpeg(tf.io.read_file(path), channels=3)
scaled = tf.cast(photo, tf.float32) / 255.0
print("Scaled:", scaled.shape, scaled.dtype)
print("Values from", tf.reduce_min(scaled).numpy(), "to", tf.reduce_max(scaled).numpy())
means = tf.reduce_mean(scaled, axis=[0, 1])
centered = scaled - means
print("Means:", means.shape, means.numpy())
print("Centered:", centered.shape)
print("Means after:", tf.reduce_mean(centered, axis=[0, 1]).numpy())
tf.cast(photo, tf.float32) / 255.0divides afloat32tensor by a decimal: both sides arefloat32now. Dividing a tensor by a single number divides every one of its values. How to Add, Subtract, Multiply and Divide Tensors in TensorFlow shows all four operations.meansholds each colour's average, so its shape is(3,).scaled - meanssubtracts a tensor of shape(3,)from one of shape(192, 240, 3). The shapes differ, and it works anyway: TensorFlow broadcasts the smaller tensor, using the same three averages for every pixel. The guide describes it: "smaller tensors are "stretched" automatically to fit larger tensors when running combined operations on them". The three averages line up with the last axis, the colours. How to Use Broadcasting in TensorFlow shows which shapes can be broadcast.- The last line averages the result, to check that each colour's average is now 0.
Run it:
uv run python scratch/scale.py
Scaled: (192, 240, 3) <dtype: 'float32'>
Values from 0.0 to 1.0
Means: (3,) [0.5427837 0.29072833 0.1336383 ]
Centered: (192, 240, 3)
Means after: [ 5.6932837e-05 6.9279781e-06 -1.9375908e-07]

Every value is now from 0.0 to 1.0, as a float32. The averages after subtracting are tiny but not exactly 0: 5.6932837e-05 means 0.000057. A computer stores decimals rounded, and averaging 46,080 of them adds those tiny errors up.
Step 6: Turn the Photo Gray with a Matrix Multiplication
A gray pixel is one number: a weighted sum of the pixel's red, green and blue. TensorFlow has a function for it, tf.image.rgb_to_grayscale, and its source code holds the weights it uses: [0.2989, 0.5870, 0.1140]. So gray = 0.2989 × red + 0.5870 × green + 0.1140 × blue. Working that out for all 46,080 pixels at once takes two tensor operations, a reshape and a matrix multiplication. Create scratch/grayscale.py:
import tensorflow as tf
path = "data/flowers/flower_photos/tulips/4042180234_64cd2859c9_m.jpg"
photo = tf.cast(tf.io.decode_jpeg(tf.io.read_file(path), channels=3), tf.float32)
height, width, channels = photo.shape
print("Photo: ", height, "x", width, "x", channels)
pixels = tf.reshape(photo, [-1, channels])
print("Pixels:", pixels.shape)
weights = tf.constant([[0.2989], [0.5870], [0.1140]])
gray = tf.reshape(pixels @ weights, [height, width, 1])
print("Gray: ", gray.shape)
print("Top-left pixel:", photo[0, 0].numpy(), "->", gray[0, 0].numpy())
expected = tf.image.rgb_to_grayscale(photo)
print("Largest difference from rgb_to_grayscale:", tf.reduce_max(tf.abs(gray - expected)).numpy())
tf.io.write_file("scratch/gray.jpg", tf.io.encode_jpeg(tf.cast(gray, tf.uint8)))

height, width, channels = photo.shapeunpacks the shape into its three numbers.tf.reshape(photo, [-1, channels])arranges the same 138,240 numbers as a table, with one row for each pixel and 3 columns.-1asks TensorFlow to work out that axis's length itself: 138,240 ÷ 3 = 46,080 rows. A reshape keeps the numbers and their order, and changes only how they're grouped. How to Reshape a Tensor in TensorFlow with tf.reshape shows what-1can and can't do.weightshas the shape(3, 1): three rows and one column.pixels @ weightsis a matrix multiplication:(46080, 3)times(3, 1)gives(46080, 1). Each pixel's three numbers are multiplied by the three weights and added up, giving one gray value for each pixel.@is Python's operator for it, and TensorFlow runstf.matmul. How to Multiply Matrices in TensorFlow with tf.matmul explains which shapes can be multiplied.- The second
tf.reshapeputs the gray values back into the photo's shape, with one channel:(192, 240, 1). - The check:
tf.image.rgb_to_grayscale(photo)makes the gray photo with TensorFlow's own function,tf.absturns every difference into a positive number, andtf.reduce_maxfinds the largest. How to Convert an Image to Grayscale in TensorFlow with rgb_to_grayscale and How to Get the Absolute Value of a Tensor with tf.abs show both functions. - The last line saves the gray photo.
tf.castturns it back intouint8,tf.io.encode_jpegturns the pixels into a JPEG file's bytes, andtf.io.write_filewrites them toscratch/gray.jpg. How to Save a Tensor as a JPEG Image in TensorFlow with encode_jpeg and How to Write a File in TensorFlow with tf.io.write_file show both.
Run it:
uv run python scratch/grayscale.py
Photo: 192 x 240 x 3
Pixels: (46080, 3)
Gray: (192, 240, 1)
Top-left pixel: [102. 88. 87.] -> [92.0618]
Largest difference from rgb_to_grayscale: 0.0

The top-left pixel, [102. 88. 87.], became 92.0618: 0.2989 × 102 + 0.5870 × 88 + 0.1140 × 87. The largest difference from TensorFlow's own function is 0.0, so one matrix multiplication made exactly the same 46,080 gray values. Here is the photo before and after:

Photo: tulips by Tristan Martin, under CC BY 2.0, converted to grayscale on the right.
Step 7: Load Photos of Different Sizes into One Batch
A model learns from a batch of photos at a time: one tensor with an extra axis in front, (photos, height, width, channels). The guide describes this order: "Often axes are ordered from global to local: The batch axis first, followed by spatial dimensions, and features for each location last."
Time for the project's own code. Create src/image_classifier/photos.py, with a function that loads one photo the way Steps 4 to 6 did:
"""Turn photo files into tensors."""
import tensorflow as tf
def load_photo(path: str | tf.Tensor) -> tf.Tensor:
"""Read a JPEG photo and return it as a uint8 tensor of shape (height, width, 3)."""
data = tf.io.read_file(path)
return tf.io.decode_jpeg(data, channels=3)
path: str | tf.Tensor says the file name can be a string or a string tensor, the form TensorFlow's input pipelines pass file names in. Then a practice script that loads one photo of each flower, the five from Part 1's grid, and stacks them into a batch. Create scratch/batch.py:
import tensorflow as tf
from image_classifier.photos import load_photo
photo_paths = {
"daisy": "data/flowers/flower_photos/daisy/7568630428_8cf0fc16ff_n.jpg",
"dandelion": "data/flowers/flower_photos/dandelion/4510350093_3700064215.jpg",
"roses": "data/flowers/flower_photos/roses/7409458444_0bfc9a0682_n.jpg",
"sunflowers": "data/flowers/flower_photos/sunflowers/3749091071_c146b33c74_n.jpg",
"tulips": "data/flowers/flower_photos/tulips/4042180234_64cd2859c9_m.jpg",
}
photos = [load_photo(path) for path in photo_paths.values()]
for name, photo in zip(photo_paths, photos):
print(f"{name:<11}{photo.shape}")
batch = tf.stack(photos)
print("Batch:", batch.shape, batch.dtype)
from image_classifier.photos import load_photoimports the project's new function. It works in a practice script becauseuv runruns it in the project's environment, where uv installed the project itself in Part 1.photo_pathsis a dictionary of each flower's name and its photo's path, andphotosis a list of the five loaded photos.- The
forloop prints each name with its photo's shape.zippairs the names with the photos, and{name:<11}pads each name to 11 characters, so the shapes line up. tf.stack(photos)puts the five photos into one tensor, along a new first axis. Its API page says it "Stacks a list of rank-R tensors into one rank-(R+1) tensor." How to Stack Tensors in TensorFlow with tf.stack shows how itsaxisargument changes where the new axis goes.
Run it:
uv run python scratch/batch.py
daisy (239, 320, 3)
dandelion (334, 500, 3)
roses (277, 320, 3)
sunflowers (220, 320, 3)
tulips (192, 240, 3)
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
W0000 00:00:1796442890.412957 89352 local_rendezvous.cc:461] Local rendezvous is aborting with status: INVALID_ARGUMENT: Shapes of all inputs must match: values[0].shape = [239,320,3] != values[1].shape = [334,500,3]
=== Source Location Trace: ===
tensorflow/core/kernels/pack_op.cc:108
tensorflow/core/common_runtime/single_threaded_executor.cc:449
tensorflow/core/common_runtime/function.cc:1418
Traceback (most recent call last):
File "/Users/you/source/dewiride-image-classifier/scratch/batch.py", line 17, in <module>
batch = tf.stack(photos)
File "/Users/you/source/dewiride-image-classifier/.venv/lib/python3.14/site-packages/tensorflow/python/util/traceback_utils.py", line 167, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/Users/you/source/dewiride-image-classifier/.venv/lib/python3.14/site-packages/tensorflow/python/framework/ops.py", line 6084, in raise_from_not_ok_status
raise core._status_to_exception(e) from None # pylint: disable=protected-access
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tensorflow.python.framework.errors_impl.InvalidArgumentError: {{function_node __wrapped__Pack_N_5_device_/job:localhost/replica:0/task:0/device:CPU:0}} Shapes of all inputs must match: values[0].shape = [239,320,3] != values[1].shape = [334,500,3] [Op:Pack] name: stack
![The terminal after uv run python scratch/batch.py: the five photos' shapes, daisy (239, 320, 3), dandelion (334, 500, 3), roses (277, 320, 3), sunflowers (220, 320, 3) and tulips (192, 240, 3), then TensorFlow's WARNING and W0000 log lines and a traceback pointing at batch = tf.stack(photos) on line 17, ending in InvalidArgumentError: Shapes of all inputs must match: values[0].shape = [239,320,3] != values[1].shape = [334,500,3] for the operation Pack.](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/ai/tensorflow/2026/tensorflow-p2-11-stack-error.webp)
All five photos loaded, each a different size, and then tf.stack stopped on line 17. The lines above the traceback are TensorFlow's own log: the WARNING line says the log is written to standard error (STDERR), which your terminal shows, and the line starting with W0000 reports the operation that failed, followed by where in TensorFlow's code it happened. The traceback after them is Python's, and its last line is the error: "Shapes of all inputs must match: values[0].shape = [239,320,3] != values[1].shape = [334,500,3]". The daisy and the dandelion aren't the same size, and [Op:Pack] names the operation that failed: Pack is the operation tf.stack runs. Here's what I checked:
- What
tf.stacktakes: its API page describes its input as "A list of Tensor objects with the same shape and type." - Why: the guide says "The base tf.Tensor class requires tensors to be "rectangular"---that is, along each axis, every element is the same size." A tensor can't have a 239-row photo and a 334-row photo side by side on one axis.
- How many sizes there are: I decoded all 3,670 photos. They come in 345 different sizes, from 159 to 442 pixels high and from 143 to 1,024 wide.
So every photo has to be brought to one size before it's stacked. Fixed: Shapes of all inputs must match … [Op:Pack] in tf.stack shows the error on its own. Resize the photos in load_photo. Replace src/image_classifier/photos.py with:
"""Turn photo files into tensors of one shape."""
import tensorflow as tf
# Every photo is resized to this height and width, so photos can be stacked into a batch.
IMAGE_SIZE = (180, 180)
def load_photo(path: str | tf.Tensor, image_size: tuple[int, int] = IMAGE_SIZE) -> tf.Tensor:
"""Read a JPEG photo and resize it to image_size, a (height, width) pair.
Returns a float32 tensor of shape (height, width, 3), with values from 0 to 255.
"""
data = tf.io.read_file(path)
photo = tf.io.decode_jpeg(data, channels=3)
return tf.image.resize(photo, image_size)

IMAGE_SIZE = (180, 180)is the height and width every photo gets. TensorFlow's own tutorial for these photos uses 180 × 180 too:img_height = 180andimg_width = 180. The name is in capitals because it's a constant, a value the code never changes, and it sits at the top of the module where later code can import it.image_size: tuple[int, int] = IMAGE_SIZEis a new parameter, a pair of whole numbers, withIMAGE_SIZEas its default, so a caller can ask for another size.tf.image.resize(photo, image_size)resizes the photo. Its API page says "The return value has type float32, unless the method is ResizeMethod.NEAREST_NEIGHBOR", so the function now returnsfloat32. The values are still from 0 to 255: resizing changes the size, not the scale. How to Resize an Image in TensorFlow with tf.image.resize works out its new pixels by hand, on a tiny picture.
Run scratch/batch.py again:
uv run python scratch/batch.py
daisy (180, 180, 3)
dandelion (180, 180, 3)
roses (180, 180, 3)
sunflowers (180, 180, 3)
tulips (180, 180, 3)
Batch: (5, 180, 180, 3) <dtype: 'float32'>

Every photo is now (180, 180, 3), and the batch is one tensor of shape (5, 180, 180, 3): 5 photos, each 180 rows of 180 pixels with 3 colours, as float32. That's the shape a model takes in. TensorFlow's tutorial uses batches of 32 photos, and its first batch has the shape (32, 180, 180, 3).
To see what resizing did to the photos, save each one from the batch as a JPEG. Add these lines to the end of scratch/batch.py:
for name, photo in zip(photo_paths, batch):
path = f"scratch/resized/{name}.jpg"
tf.io.write_file(path, tf.io.encode_jpeg(tf.cast(photo, tf.uint8)))
print("Saved", path)
A for loop over the batch gives you its photos one at a time, along its first axis. How to Loop over a Tensor in TensorFlow with for shows what each step of such a loop gets. tf.io.write_file creates the missing resized folder by itself. Run the script:
uv run python scratch/batch.py
daisy (180, 180, 3)
dandelion (180, 180, 3)
roses (180, 180, 3)
sunflowers (180, 180, 3)
tulips (180, 180, 3)
Batch: (5, 180, 180, 3) <dtype: 'float32'>
Saved scratch/resized/daisy.jpg
Saved scratch/resized/dandelion.jpg
Saved scratch/resized/roses.jpg
Saved scratch/resized/sunflowers.jpg
Saved scratch/resized/tulips.jpg
The five saved photos look like this:

Photos, left to right: daisy by A Guy Taking Pictures, dandelion by seyed mostafa zamani, roses by Rosa Dik 009 -- on & off, sunflowers by Vincent_AF and tulips by Tristan Martin, all under CC BY 2.0, resized to 180 × 180 pixels.
Every photo is square now, so the ones that weren't are squeezed. The dandelion was 500 pixels wide and 334 high, and lost more of its width than of its height. The resize API page warns about this: "Resized images will be distorted if their original aspect ratio is not the same as size." TensorFlow's own tutorial resizes these photos the same way.
Step 8: Commit the New Code
Check what Git would commit:
git status
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: .gitignore
Untracked files:
(use "git add <file>..." to include in what will be committed)
src/image_classifier/photos.py
no changes added to commit (use "git add" and/or "git commit -a")
.gitignore changed and photos.py is new. The scratch folder isn't listed: Git ignores it now. Commit both:
git add .
git commit -m "Load photos as tensors of one shape"
[main a2674bd] Load photos as tensors of one shape
2 files changed, 19 insertions(+)
create mode 100644 src/image_classifier/photos.py

Your Project Now Looks Like This
dewiride-image-classifier/
├── .gitignore
├── .python-version
├── README.md
├── data/
│ ├── flowers/
│ │ └── flower_photos/
│ └── flowers_archive
├── pyproject.toml
├── scratch/
│ ├── batch.py
│ ├── data_types.py
│ ├── first_tensors.py
│ ├── gray.jpg
│ ├── grayscale.py
│ ├── photo_tensor.py
│ ├── resized/
│ │ ├── daisy.jpg
│ │ ├── dandelion.jpg
│ │ ├── roses.jpg
│ │ ├── sunflowers.jpg
│ │ └── tulips.jpg
│ ├── scale.py
│ └── tiny_photo.py
├── src/
│ └── image_classifier/
│ ├── __init__.py
│ ├── cli.py
│ ├── data.py
│ └── photos.py
└── uv.lock
As in Part 1, the tree leaves out .venv, .git and src/image_classifier/__pycache__/. The only new file Git keeps is src/image_classifier/photos.py; scratch stays on your computer.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Changing a pixel in place: photo[0, 0] = [255, 255, 255] | TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment: a tensor can't be changed | Make a new tensor with the change. Fixed: TypeError: 'EagerTensor' object does not support item assignment shows how |
Passing a pathlib.Path to load_photo | ValueError: Attempt to convert a value (PosixPath('data/flowers/…')) with an unsupported type (<class 'pathlib.PosixPath'>) to a Tensor. | Pass str(path). Fixed: ValueError: Attempt to convert a value (PosixPath(…)) with an unsupported type to a Tensor explains why |
Adding a float32 tensor to a uint8 one: pixels + tf.constant([10.0, 10.0, 10.0]) | InvalidArgumentError: cannot compute AddV2 as input #1(zero-based) was expected to be a uint8 tensor but is a float tensor [Op:AddV2] | Convert the uint8 tensor first: tf.cast(pixels, tf.float32). Fixed: cannot compute AddV2 as input #1(zero-based) was expected to be a uint8 tensor but is a float tensor explains the message |
Dividing a uint8 photo by 255.0 | TypeError ending in got tf.uint8 != tf.float32. | tf.cast(photo, tf.float32) / 255.0, as in Step 5 |
Averaging or adding up uint8 values | Averages lose their decimals, and sums past 255 wrap around to small numbers | Convert to float32 first, as in Steps 3 and 4 |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
NotFoundError: … data/flowers/flower_photos/daisy/7568630428_8cf0fc16ff_n.jpg; No such file or directory [Op:ReadFile] | You ran the script inside scratch. The photos' paths start from the folder you run the command in | Run it from the project folder: uv run python scratch/batch.py. Fixed: NotFoundError: No such file or directory [Op:ReadFile] explains why |
InvalidArgumentError: … Shapes of all inputs must match … [Op:Pack] | Photos of different sizes passed to tf.stack | Resize them first, as load_photo does in Step 7 |
Lines starting with WARNING or W0000 before an error | TensorFlow's own log of the operation that failed | Read the last line of the traceback: that's the error |
FAQ
What's the difference between a tensor and a NumPy array?
Both are grids of numbers of one type, and the guide says that "tensors are (kind of) like np.arrays". .numpy() turns a tensor into a NumPy array. The difference you'll notice first: you can change a NumPy array in place, and you can't change a tensor. The other one matters later: TensorFlow's basics guide says that "When properly configured, TensorFlow can use accelerator hardware like GPUs to execute operations very quickly."
Why does a model need float32 and not uint8?
A uint8 holds only whole numbers from 0 to 255, so it can't hold a scaled pixel such as 0.54, and Step 3 showed how its sums wrap around. TensorFlow's tutorial asks for small input values, from 0 to 1, and those need decimals.
Can I resize a photo without squeezing it?
Yes. The tf.image.resize API page says: "To avoid distortions see tf.image.resize_with_pad." That function keeps the photo's proportions and fills the space left over with zeros, which are black pixels: its API page says the image "is resized and then padded with zeroes to match requested dimensions." This series squeezes, as TensorFlow's own tutorial for these photos does.
Why 180 × 180 pixels?
It's the size TensorFlow's own tutorial uses for these photos. Smaller photos also mean fewer numbers for a model to work through: a 180 × 180 photo is 97,200 numbers, while the dandelion photo was 501,000.
Clean Up
Nothing runs in the background, so there's nothing to stop. Keep the project, the photos and the scratch folder: later parts add their practice scripts to scratch, and Part 3 starts from this project.
Conclusion
You met the tensor: a grid of numbers with a shape, a rank, a size and a data type. You turned a flower photo into a uint8 tensor of shape (192, 240, 3), picked pixels and channels out of it, converted it to float32 and scaled it from 0–255 to 0–1, and used broadcasting to subtract each colour's average. One reshape and one matrix multiplication turned it gray, exactly as tf.image.rgb_to_grayscale does. And the project has new code of its own: load_photo, which reads any of the 3,670 photos and resizes it to 180 × 180, so five photos of five sizes stacked into one batch of shape (5, 180, 180, 3).
On the way you met four problems worth remembering: a uint8 sum that wrapped around, an average that lost its decimals, a division between two data types, and photos of different sizes that wouldn't stack.
In Part 3 you'll meet the tensors that can change, variables, and tf.GradientTape, which works out how to change them so a model learns.
Additional Resources
- Introduction to Tensors — TensorFlow's guide: shapes, indexing, reshaping and broadcasting.
- tf.dtypes — every data type TensorFlow has.
- tf.image — TensorFlow's image operations, from resizing to colour conversion.
- Load and preprocess images — TensorFlow's tutorial with the same flower photos.
← Previous: Part 1: Install TensorFlow and Set Up Your First Project
Next → Part 3: Variables and Automatic Differentiation with GradientTape (coming soon)
