Skip to main content

TensorFlow Tutorial for Deep Learning in Python — Part 2: Tensors: Shapes, Data Types and Operations

· 38 min read
Jagdish Kumawat
Founder @ Dewiride

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.

  1. Part 1: Install TensorFlow and Set Up Your First Project
  2. Part 2: Tensors: Shapes, Data Types and Operations (you are here)
  3. Part 3: Variables and Automatic Differentiation with GradientTape (coming soon)
  4. Part 4: Build an Image Input Pipeline with tf.data (coming soon)
  5. Part 5: Build Your First Neural Network with Keras (coming soon)
  6. Part 6: Build a Convolutional Neural Network (coming soon)
  7. Part 7: Monitor Training with Callbacks and TensorBoard (coming soon)
  8. Part 8: Reduce Overfitting with Data Augmentation and Dropout (coming soon)
  9. Part 9: Transfer Learning and Fine-Tuning with a Pretrained Model (coming soon)
  10. Part 10: Evaluate a Classifier: Confusion Matrix, Precision and Recall (coming soon)
  11. Part 11: Save, Load and Export a Keras Model (coming soon)
  12. Part 12: Text Classification with TextVectorization (coming soon)
  13. Part 13: Word Embeddings and LSTM Networks for Text (coming soon)
  14. Part 14: Time Series Forecasting: Windows, Normalization and Baselines (coming soon)
  15. Part 15: Forecast with LSTM and Conv1D Models (coming soon)
  16. Part 16: Write a Custom Training Loop with tf.function (coming soon)
  17. Part 17: Convert a Keras Model to LiteRT (coming soon)
  18. Part 18: Serve TensorFlow Models with FastAPI (coming soon)
  19. 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:

WordWhat it meansFor a colour photo 192 pixels high and 240 wide
ShapeHow many items lie along each axis(192, 240, 3): 192 rows, 240 pixels in each row, 3 colours in each pixel
RankHow many axes it has3
SizeHow many numbers it holds: the numbers of its shape multiplied together192 × 240 × 3 = 138,240
Data type (dtype)The kind of number every item isuint8: 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​

ToolVersion
Python3.14.10
uv0.13.10
TensorFlow2.22.0
NumPy2.5.5
Git2.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​

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:

Terminal
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:

.gitignore (the end)
# Practice scripts from the tutorial, not part of the app
scratch/

Now create scratch/first_tensors.py:

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:

Terminal
uv run python scratch/first_tensors.py
Output
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)

The terminal after mkdir scratch and uv run python scratch/first_tensors.py: tf.Tensor(7, shape=(), dtype=int32), tf.Tensor of 0.5, 1.5 and 2.5 with shape (3,) and dtype float32, and a tf.Tensor of two rows, 1 2 3 and 4 5 6, with shape (2, 3) and dtype int32.

Each tensor prints as tf.Tensor(, then its values, its shape and its data type:

  • number has the shape (), which is empty: a single number has no axes. Its type is int32, a 32-bit whole number, which is what TensorFlow makes of whole numbers unless you ask for another type.
  • numbers has the shape (3,): one axis, with three items. The comma is how Python writes a tuple with one item. Decimals become float32, 32-bit decimal numbers.
  • table has 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:

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:

Terminal
uv run python scratch/tiny_photo.py
Output
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]]]

The terminal after uv run python scratch/tiny_photo.py: Shape (2, 4, 3), Rank 3, Size 24, Type int32, then the tiny photo's two rows of four pixels, each pixel three numbers.

  • 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. ndim is short for "number of dimensions", NumPy's word for axes.
  • Size 24: 2 × 4 × 3 numbers. tf.size returns 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:

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:

Terminal
uv run python scratch/data_types.py
Output
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)

The terminal after uv run python scratch/data_types.py: uint8 holds 0 to 255 in 1 byte, float32 uses 4 bytes, the uint8 pixels 0, 128 and 255, then pixels plus 50 as 50, 178 and 49, and the float32 copy plus 50 as 50., 178. and 305.

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:

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())

Run it:

Terminal
uv run python scratch/photo_tensor.py
Output
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 terminal after uv run python scratch/photo_tensor.py: the file is a string tensor of shape (), the photo a uint8 tensor of shape (192, 240, 3), the top-left pixel is 102 88 87, the red channel has shape (192, 240), the top half (96, 240, 3), the values go from 0 to 255, and the mean of each channel is 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 :96 keeps 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:

scratch/photo_tensor.py (the last line)
print("Mean of each channel:", tf.reduce_mean(tf.cast(photo, tf.float32), axis=[0, 1]).numpy())

Run it again:

Terminal
uv run python scratch/photo_tensor.py
Output
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]

The terminal after running uv run python scratch/photo_tensor.py again: the same lines as before, and now the mean of each channel is 138.42413, 74.13952 and 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:

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:

Terminal
uv run python scratch/scale.py
Output
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 terminal after uv run python scratch/scale.py: a traceback pointing at line 6, scaled = photo / 255.0, through TensorFlow's _truediv_python3 in math_ops.py, ending in 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:

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 = 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.0 divides a float32 tensor by a decimal: both sides are float32 now. 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.
  • means holds each colour's average, so its shape is (3,).
  • scaled - means subtracts 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:

Terminal
uv run python scratch/scale.py
Output
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]

The terminal after the fix: Scaled (192, 240, 3) float32, values from 0.0 to 1.0, Means with shape (3,) of 0.5427837, 0.29072833 and 0.1336383, Centered (192, 240, 3), and Means after of 5.69e-05, 6.93e-06 and -1.94e-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:

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)))

The complete scratch/grayscale.py in a macOS-style code window: it loads the tulip as float32, reshapes it to one row per pixel, multiplies the pixels by a column of three weights with the @ operator, reshapes the result back to height, width and 1, compares it with tf.image.rgb_to_grayscale, and saves it as scratch/gray.jpg.

Run it:

Terminal
uv run python scratch/grayscale.py
Output
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 terminal after uv run python scratch/grayscale.py: Photo 192 x 240 x 3, Pixels (46080, 3), Gray (192, 240, 1), the top-left pixel 102., 88., 87. becoming 92.0618, and a largest difference from rgb_to_grayscale of 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:

The tulip photo twice, side by side: on the left in colour, two red and yellow tulips in front of a blurred purple and green background, and on the right the same photo in grayscale, read from scratch/gray.jpg.

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:

src/image_classifier/photos.py
"""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:

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_photo imports the project's new function. It works in a practice script because uv run runs it in the project's environment, where uv installed the project itself in Part 1.
  • photo_paths is a dictionary of each flower's name and its photo's path, and photos is a list of the five loaded photos.
  • The for loop prints each name with its photo's shape. zip pairs 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 its axis argument changes where the new axis goes.

Run it:

Terminal
uv run python scratch/batch.py
Output
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.

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.stack takes: 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:

src/image_classifier/photos.py
"""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)

The complete src/image_classifier/photos.py in a macOS-style code window: the IMAGE_SIZE constant of 180 by 180, and load_photo, which reads the file with tf.io.read_file, decodes it with tf.io.decode_jpeg with 3 channels, and returns it resized with tf.image.resize.

  • 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 = 180 and img_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_SIZE is a new parameter, a pair of whole numbers, with IMAGE_SIZE as 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 returns float32. 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:

Terminal
uv run python scratch/batch.py
Output
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'>

The terminal after running uv run python scratch/batch.py again: all five photos, daisy, dandelion, roses, sunflowers and tulips, now have the shape (180, 180, 3), and the batch has the shape (5, 180, 180, 3) and the type 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:

scratch/batch.py (the end)
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:

Terminal
uv run python scratch/batch.py
Output
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:

The five photos from scratch/resized, each now 180 by 180 pixels: a daisy, a dandelion, roses, sunflowers and the tulip. The photos that weren't square were squeezed from the sides to fit, most of all the dandelion, which was 500 pixels wide and 334 high.

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:

Terminal
git status
Output
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:

Terminal
git add .
git commit -m "Load photos as tensors of one shape"
Output
[main a2674bd] Load photos as tensors of one shape
2 files changed, 19 insertions(+)
create mode 100644 src/image_classifier/photos.py

The terminal after git status, git add and git commit: .gitignore modified and src/image_classifier/photos.py untracked, then the commit Load photos as tensors of one shape on main, with 2 files changed and 19 insertions.

Your Project Now Looks Like This​

dewiride-image-classifier/
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​

MistakeWhat happensDo 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 changedMake a new tensor with the change. Fixed: TypeError: 'EagerTensor' object does not support item assignment shows how
Passing a pathlib.Path to load_photoValueError: 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.0TypeError ending in got tf.uint8 != tf.float32.tf.cast(photo, tf.float32) / 255.0, as in Step 5
Averaging or adding up uint8 valuesAverages lose their decimals, and sums past 255 wrap around to small numbersConvert to float32 first, as in Steps 3 and 4

Troubleshooting​

SymptomLikely causeFix
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 inRun 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.stackResize them first, as load_photo does in Step 7
Lines starting with WARNING or W0000 before an errorTensorFlow's own log of the operation that failedRead 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​


← Previous: Part 1: Install TensorFlow and Set Up Your First Project

Next → Part 3: Variables and Automatic Differentiation with GradientTape (coming soon)