Skip to main content

TensorFlow Tutorial for Deep Learning in Python — Part 1: Install TensorFlow and Set Up Your First Project

· 34 min read
Jagdish Kumawat
Founder @ Dewiride

TensorFlow is Google's open-source library for deep learning, and Keras is the library you build its models with. In this first part you install TensorFlow 2.22 in a Python 3.14 project, check what it runs on, find out where its slow first import goes, and download the 3,670 flower photos that the series' first model learns to tell apart.

This is Part 1 of a 19-part series.

  1. Part 1: Install TensorFlow and Set Up Your First Project (you are here)
  2. Part 2: Tensors: Shapes, Data Types and Operations (coming soon)
  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 You'll Have at the End of the Series​

Each part teaches one TensorFlow concept in depth and uses it on real projects. By the end of Part 19 you'll know how to:

  • work with tensors and gradients, the two ideas everything else is built on (Parts 2 and 3);
  • feed data to a model quickly with tf.data (Part 4);
  • build and train neural networks with Keras, from a first network to a convolutional one (Parts 5 and 6);
  • watch training, fight overfitting and reuse a pretrained model (Parts 7 to 9);
  • measure a classifier properly, then save, load and export it (Parts 10 and 11);
  • classify text and forecast a time series (Parts 12 to 15);
  • write your own training loop with tf.function (Part 16);
  • ship a model to phones with LiteRT and to the web with FastAPI (Parts 17 and 18);
  • run it safely in production, with a checklist (Part 19).

Everything runs on your own computer, with free, open-source software. You don't need a GPU: the series is built on a laptop's CPU.

What TensorFlow and Keras Are​

Deep learning trains a neural network, a model made of layers of simple maths, on examples. Show a network thousands of labelled flower photos, and it learns to tell the flowers apart in photos it has never seen. Two libraries do that work in this series:

NameWhat it is
TensorFlowAn open-source machine-learning library from Google. Its PyPI page sums it up: "TensorFlow is an open source machine learning framework for everyone." It does the maths on the CPU or a GPU, and runs, saves and exports trained models
KerasThe library you build and train models with. Keras 3 is a separate project that runs on top of a backend, the library that does its maths. Its documentation says Keras "supports multiple pluggable backends", with jax, torch and tensorflow as the current options. Installing TensorFlow installs Keras too

Both work on tensors: grids of numbers with a shape. A colour photo, for example, is a grid of height × width × 3 numbers, one for each pixel's red, green and blue. Part 2 is all about them.

The Example Projects​

The series is about TensorFlow, not about one app, so three projects grow behind the parts, one for each kind of data deep learning is often used on:

ProjectWhat it learnsIts data
Image classifierTells five kinds of flowers apart in a photo3,670 flower photos from TensorFlow's example data, each under the CC BY 2.0 license
Spam detectorSays whether a text message is spamThe SMS Spam Collection: 5,574 text messages, from the UCI Machine Learning Repository
Energy forecasterPredicts a home's electricity use for the hours aheadAlmost four years of minute-by-minute readings from one household, from the UCI Machine Learning Repository

This part starts the image classifier: a project with a download command that fetches the photos and counts them.

Versions Used​

ToolVersion
Python3.14.10
uv0.13.10
TensorFlow2.22.0
Keras3.15.1
NumPy2.5.5
Git2.56.1

The outputs were captured on a Mac with an Apple M1 Pro. TensorFlow runs on its CPU: Step 4 shows why. Where a command differs on Windows, a PowerShell tab shows it.

Why Python 3.14 and Not 3.15​

Python 3.15 is the newest Python, but TensorFlow 2.22.0 doesn't support it. Its release notes say "supporting Python 3.10–3.14", and on Python 3.15, uv add tensorflow fails. Fixed: "all versions of tensorflow have no wheels with a matching Python version tag (e.g., cp315)" shows the error and the fix. So the project uses Python 3.14.

What This Part Costs​

Nothing. TensorFlow, Keras and uv are free, open-source software, the photos are free to use with credit (Step 9), and everything runs on your own computer. You need about 2 GB of disk space: 1.4 GB for the project's packages and about 450 MB for the photos, which come as a 229 MB download.

Prerequisites​

  • uv, which creates Python projects and installs packages. It also downloads Python 3.14 if your computer doesn't have it. Check uv:
Terminal
uv --version
Output
uv 0.13.10 (e3e7c1eac 2026-11-24 aarch64-apple-darwin)
  • Git, to commit the project. Check it:
Terminal
git --version
Output
git version 2.56.1
  • An internet connection, for the packages and the photos.

Step 1: Create the Project​

Terminal
uv init --package --name image-classifier --python 3.14 dewiride-image-classifier
Output
Initialized project `image-classifier` at `/Users/you/source/dewiride-image-classifier`

The terminal after uv init: Initialized project image-classifier at /Users/you/source/dewiride-image-classifier.

PartWhat it does
--packageMakes an installable project, with its code in a src/ folder and a command of its own
--name image-classifierThe project's name; its Python package becomes image_classifier
--python 3.14Uses Python 3.14 and records it in .python-version
dewiride-image-classifierThe folder to create

How to Create a Python Project with uv explains every uv init option. uv also made the folder a Git repository. Move into it and name its branch main:

Terminal
cd dewiride-image-classifier
git branch -m main

git branch -m main renames the branch Git created, and prints nothing.

Step 2: Add TensorFlow​

Terminal
uv add tensorflow
Output
Using CPython 3.14.10
Creating virtual environment at: .venv
Resolved 32 packages in 2.19s
Built image-classifier @ file:///Users/you/source/dewiride-image-classifier
Prepared 32 packages in 1m 18s
Installed 32 packages in 238ms
+ absl-py==2.5.1
+ astunparse==1.6.3
+ certifi==2026.11.20
+ charset-normalizer==3.5.3
+ flatbuffers==25.12.19
+ gast==0.7.0
+ google-pasta==0.2.0
+ grpcio==1.86.0
+ h5py==3.15.1
+ idna==3.20
+ image-classifier==0.1.0 (from file:///Users/you/source/dewiride-image-classifier)
+ keras==3.15.1
+ libclang==18.1.1
+ markdown-it-py==4.3.0
+ mdurl==0.1.2
+ ml-dtypes==0.7.0
+ namex==0.1.0
+ numpy==2.5.5
+ opt-einsum==3.4.0
+ optree==0.20.0
+ packaging==26.4
+ protobuf==7.36.2
+ pygments==2.21.0
+ requests==2.34.2
+ rich==15.0.0
+ six==1.17.0
+ tensorflow==2.22.0
+ termcolor==3.3.0
+ typing-extensions==4.16.0
+ urllib3==2.8.0
+ wheel==0.48.0
+ wrapt==2.5.2

The terminal after uv add tensorflow: uv used CPython 3.14.10, created .venv, resolved 32 packages, prepared them in 1 minute 18 seconds and installed them, among them h5py 3.15.1, keras 3.15.1, numpy 2.5.5, protobuf 7.36.2 and tensorflow 2.22.0.

uv created the project's environment, .venv, with Python 3.14.10, and installed 32 packages: TensorFlow 2.22.0, the 30 packages it needs, and the project itself. Downloading and unpacking them took 1 minute 18 seconds here. Two of them matter from the start:

PackageWhat it does
kerasKeras 3.15.1, the library you'll build models with
numpyNumPy 2.5.5, a library for arrays of numbers. TensorFlow turns its tensors into NumPy arrays and back

How to Add a Package to a Python Project with uv covers uv add in detail.

TensorBoard isn't included

Older TensorFlow releases installed TensorBoard, the tool for watching a model train, with them. TensorFlow 2.22.0 doesn't: its release notes say "The TensorBoard dependency is no longer included by default." Part 7 adds it when the project needs it.

Step 3: Check the Versions​

Terminal
uv run python -c "import tensorflow as tf, keras; print(tf.__version__, keras.__version__)"
Output
2.22.0 3.15.1

uv run runs a command inside the project's environment, and python -c runs the code in quotes. That code imports TensorFlow, under the short name tf that TensorFlow's own documentation uses, and Keras, and prints their versions: TensorFlow 2.22.0 and Keras 3.15.1. How to Check Which Version of TensorFlow Is Installed shows TensorFlow's build details too, and how to check the version without importing it.

That command took 46 seconds, with nothing on the screen until the versions appeared. Run it again:

Terminal
uv run python -c "import tensorflow as tf, keras; print(tf.__version__, keras.__version__)"
Output
2.22.0 3.15.1

The terminal after running the version check twice: both runs printed 2.22.0 3.15.1.

This time it took 2 seconds.

Why the First Import Is So Slow​

46 seconds the first time, 2 seconds after. You'll meet this again whenever the environment is created anew, so it's worth knowing where the time goes.

My first guess was bytecode. Python compiles each module to bytecode the first time it's imported, and saves it for next time, and uv doesn't compile anything when it installs. TensorFlow alone has 1,846 Python files, so that seemed to explain it. To test the guess, delete the environment and create it again, this time with the bytecode compiled while installing:

Terminal
rm -rf .venv
uv sync --compile-bytecode
Output (macOS)
Using CPython 3.14.10
Creating virtual environment at: .venv
Resolved 32 packages in 7ms
Installed 32 packages in 389ms
Bytecode compiled 4105 files in 1.57s
+ absl-py==2.5.1
+ astunparse==1.6.3
+ certifi==2026.11.20
+ charset-normalizer==3.5.3
+ flatbuffers==25.12.19
+ gast==0.7.0
+ google-pasta==0.2.0
+ grpcio==1.86.0
+ h5py==3.15.1
+ idna==3.20
+ image-classifier==0.1.0 (from file:///Users/you/source/dewiride-image-classifier)
+ keras==3.15.1
+ libclang==18.1.1
+ markdown-it-py==4.3.0
+ mdurl==0.1.2
+ ml-dtypes==0.7.0
+ namex==0.1.0
+ numpy==2.5.5
+ opt-einsum==3.4.0
+ optree==0.20.0
+ packaging==26.4
+ protobuf==7.36.2
+ pygments==2.21.0
+ requests==2.34.2
+ rich==15.0.0
+ six==1.17.0
+ tensorflow==2.22.0
+ termcolor==3.3.0
+ typing-extensions==4.16.0
+ urllib3==2.8.0
+ wheel==0.48.0
+ wrapt==2.5.2

The terminal after deleting .venv and running uv sync --compile-bytecode: a new .venv with CPython 3.14.10, 32 packages installed in 389 milliseconds, and Bytecode compiled 4105 files in 1.57s.

uv sync installs every package that uv.lock lists, from uv's cache this time, so installing took 389 milliseconds. --compile-bytecode then compiled 4,105 files in 1.57 seconds. How to Make Python Packages Import Faster the First Time with uv --compile-bytecode explains the option.

Now import TensorFlow in the new environment, and measure it. -X importtime makes Python report how long each import takes, in microseconds. The report goes to standard error, the stream for messages, so 2> saves it to a file, imports.txt. Then print the file's last line and its three slowest imports:

Terminal
uv run python -X importtime -c "import tensorflow" 2> imports.txt
tail -n 1 imports.txt
sort -t: -k2 -n imports.txt | tail -n 3
Output (macOS)
import time: 6394 | 51990253 | tensorflow
import time: 966149 | 966149 | tensorflow.python.profiler.internal._pywrap_profiler_plugin
import time: 1002277 | 1002277 | ml_dtypes._ml_dtypes_ext
import time: 14139447 | 14139447 | tensorflow.python.platform._pywrap_cpu_feature_guard

The terminal after timing the import with -X importtime: the last line shows tensorflow with a cumulative 51990253 microseconds, and the three slowest imports are _pywrap_profiler_plugin at 966149, ml_dtypes._ml_dtypes_ext at 1002277 and tensorflow.python.platform._pywrap_cpu_feature_guard at 14139447.

Each line of the report reads self | cumulative | module: the time spent in that module alone, then the time including every module it imported.

  • The last line is tensorflow itself: 51,990,253 microseconds in all, 52 seconds. Compiling the bytecode didn't make the first import any faster, so the guess was wrong.
  • The sort splits each line at : and sorts by the number after it, the self time. tail -n 3 keeps the three slowest. In PowerShell, Select-Object -Skip 1 skips the report's header line, Sort-Object sorts by the same number, and Select-Object -Last 3 keeps the three slowest.

One module stands out: tensorflow.python.platform._pywrap_cpu_feature_guard, 14.1 seconds on its own. It isn't Python but compiled code, so there's no bytecode to compile. It's also the first module that needs TensorFlow's two big libraries: macOS's otool -L, which lists the libraries a compiled file needs, shows libtensorflow_cc, about 740 MB, and libtensorflow_framework, 53 MB, and they're loaded together with the module. Every other module took about a second or less on its own: the rest of the 52 seconds is spread over the many other modules TensorFlow imports.

Running the same three commands again printed:

Output (macOS)
import time: 6429 | 2049969 | tensorflow
import time: 30909 | 30909 | tensorflow.python.profiler.internal._pywrap_profiler_plugin
import time: 36143 | 40356 | tensorflow.python.keras.backend
import time: 397098 | 397098 | tensorflow.python.platform._pywrap_cpu_feature_guard

2 seconds for the whole import, and 0.4 seconds for that module. So the first import is slow once for each new environment, its biggest single cost is loading TensorFlow's compiled libraries, and compiling the bytecode didn't change it. I found no TensorFlow or Python documentation that explains why a first load takes so long, so this page only reports what I measured. There's nothing to fix: let the first import finish, and every import after it takes about 2 seconds.

Delete the report, so it doesn't end up in Git:

Terminal
rm imports.txt

Step 4: Check What TensorFlow Runs On​

Terminal
uv run python -c "import tensorflow as tf; print(tf.config.list_physical_devices())"
Output
[PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]

tf.config.list_physical_devices() lists every device TensorFlow can run on. On this Mac there's one: the CPU. Ask for GPUs only:

Terminal
uv run python -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"
Output
[]

An empty list: no GPU. TensorFlow's install page says why: "There is currently no official GPU support for MacOS." On Linux with an NVIDIA graphics card, TensorFlow uses the GPU once it's installed as tensorflow[and-cuda]. On Windows, the same page says TensorFlow 2.10 "was the last TensorFlow release that supported GPU on native-Windows", and for a GPU it points to WSL2, Linux running inside Windows. I didn't test either. How to Check Whether TensorFlow Can Use a GPU shows how to see what your TensorFlow was built for.

Last, the check that TensorFlow's install page gives to verify an installation:

Terminal
uv run python -c "import tensorflow as tf; print(tf.reduce_sum(tf.random.normal([1000, 1000])))"
Output
tf.Tensor(628.3007, shape=(), dtype=float32)

The terminal after the three device checks: list_physical_devices printed one PhysicalDevice, the CPU, list_physical_devices with GPU printed an empty list, and the reduce_sum check printed tf.Tensor(628.3007, shape=(), dtype=float32).

tf.random.normal([1000, 1000]) makes a tensor of 1,000 × 1,000 random numbers, and tf.reduce_sum adds them all up. The answer is a tensor too, printed with its value, its shape, (), which means a single number, and its data type, float32. Your number will be different, because the numbers are random. TensorFlow works.

Is a CPU enough? For this series, yes: it's built on this Mac's CPU, and each part that trains a model says how long training took.

Step 5: Set the Keras Backend​

Keras 3 can run on TensorFlow, JAX or PyTorch. It reads its choice from the KERAS_BACKEND environment variable, or from a settings file, keras.json, in a .keras folder in your home folder, and uses TensorFlow when neither says otherwise. A setting left on your computer by another project would change that, so this project sets the backend itself.

Open src/image_classifier/__init__.py. uv wrote a main function there:

src/image_classifier/__init__.py (as uv wrote it)
def main() -> None:
print("Hello from image-classifier!")

Replace the whole file with this:

src/image_classifier/__init__.py
"""Train a flower photo classifier with TensorFlow and Keras."""

import os

# Keras 3 runs on TensorFlow, JAX or PyTorch. It reads its choice from the KERAS_BACKEND
# environment variable or from ~/.keras/keras.json. This project uses TensorFlow, so it sets
# the backend before any of its modules imports Keras.
os.environ["KERAS_BACKEND"] = "tensorflow"

The new src/image_classifier/init.py in a macOS-style code window: a docstring, import os, a comment explaining that Keras 3 reads its backend from KERAS_BACKEND or keras.json, and the line that sets os.environ KERAS_BACKEND to tensorflow.

  • The first line is the package's docstring: a sentence that says what the package is for.
  • os.environ holds the program's environment variables. The last line sets KERAS_BACKEND to tensorflow, for this program only.
  • Why here: Python runs a package's __init__.py before any of its modules, so the setting is in place before any module of the project imports Keras. Keras reads it when it's imported, and later is too late.

How to Set the Keras Backend with KERAS_BACKEND shows the other ways to choose a backend, and what happens when it's set too late. The main function moves to a file of its own in Step 7.

Step 6: Write the Download Code​

The photos are TensorFlow's own example data: one archive, flower_photos.tgz, with a folder for each kind of flower. Create src/image_classifier/data.py. It starts with where to download from, and how to check the download:

src/image_classifier/data.py (the top)
"""Download the flower photos and count them."""

from pathlib import Path

import keras

PHOTOS_URL = (
"https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
)
# The archive's SHA-256, as TensorFlow Datasets publishes it (tf_flowers checksums.tsv).
PHOTOS_SHA256 = "4c54ace7911aaffe13a365c34f650e71dd5bf1be0a58b464e5a7183e3e595d9c"
PHOTO_SUFFIXES = {".jpg", ".jpeg", ".png"}
  • PHOTOS_URL is the archive's address, the one TensorFlow's image loading tutorial downloads too.
  • PHOTOS_SHA256 is the archive's SHA-256 hash: a fingerprint of the file that changes if a single byte of it does. TensorFlow Datasets publishes it in its checksums file for these photos, with the size, 228,813,984 bytes. Checking the download against it means the project never uses a damaged file, or one that isn't what it expects.
  • PHOTO_SUFFIXES lists the file endings that count as photos.

Next, the function that downloads and unpacks the archive:

src/image_classifier/data.py (download_photos)
def download_photos(data_dir: Path) -> Path:
"""Download and extract the flower photos, and return the folder of class folders."""
data_dir = data_dir.resolve()
data_dir.mkdir(parents=True, exist_ok=True)
extracted = keras.utils.get_file(
fname="flowers",
origin=PHOTOS_URL,
file_hash=PHOTOS_SHA256,
extract=True,
cache_dir=data_dir,
cache_subdir="",
)
return Path(extracted) / "flower_photos"
  • data_dir.resolve() turns the folder into a full path, so the command can show exactly where the photos are, and mkdir creates the folder if it doesn't exist yet.
  • keras.utils.get_file downloads the archive, checks it against the hash, unpacks it, and returns the folder it unpacked into. When the archive is already there, it checks that copy instead of downloading it again.
    • fname="flowers" names the unpacked folder flowers. The archive itself is kept beside it as flowers_archive.
    • cache_dir=data_dir, with cache_subdir="", keeps both in the project's data folder instead of the .keras/datasets folder in your home folder, which every project shares.
  • The return value: the archive holds a single folder, flower_photos, so the function returns that.

How to Download and Extract a Dataset with keras.utils.get_file shows each of these arguments on its own.

Last, a function that counts the photos:

src/image_classifier/data.py (count_photos)
def count_photos(photos_dir: Path) -> dict[str, int]:
"""Count the photos in each class folder, by class name, in alphabetical order."""
return {
folder.name: sum(1 for file in folder.iterdir() if file.suffix.lower() in PHOTO_SUFFIXES)
for folder in sorted(photos_dir.iterdir())
if folder.is_dir()
}

Each folder in flower_photos is a class: here that means a category, one kind of flower the model will learn, not a Python class. The folder's name is the class's name. The function goes through the folders in alphabetical order, skips anything that isn't a folder, and counts the files in each whose ending, in lower case, is in PHOTO_SUFFIXES. It returns each class's name with its count, such as {"daisy": 633, ...}.

The complete file:

src/image_classifier/data.py
"""Download the flower photos and count them."""

from pathlib import Path

import keras

PHOTOS_URL = (
"https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
)
# The archive's SHA-256, as TensorFlow Datasets publishes it (tf_flowers checksums.tsv).
PHOTOS_SHA256 = "4c54ace7911aaffe13a365c34f650e71dd5bf1be0a58b464e5a7183e3e595d9c"
PHOTO_SUFFIXES = {".jpg", ".jpeg", ".png"}


def download_photos(data_dir: Path) -> Path:
"""Download and extract the flower photos, and return the folder of class folders."""
data_dir = data_dir.resolve()
data_dir.mkdir(parents=True, exist_ok=True)
extracted = keras.utils.get_file(
fname="flowers",
origin=PHOTOS_URL,
file_hash=PHOTOS_SHA256,
extract=True,
cache_dir=data_dir,
cache_subdir="",
)
return Path(extracted) / "flower_photos"


def count_photos(photos_dir: Path) -> dict[str, int]:
"""Count the photos in each class folder, by class name, in alphabetical order."""
return {
folder.name: sum(1 for file in folder.iterdir() if file.suffix.lower() in PHOTO_SUFFIXES)
for folder in sorted(photos_dir.iterdir())
if folder.is_dir()
}

The complete src/image_classifier/data.py in a macOS-style code window: the photos' URL and SHA-256, download_photos, which calls keras.utils.get_file with fname flowers, the hash, extract True and the project's data folder, and count_photos, which counts the photo files in each class folder.

Step 7: Add the download Command​

Thanks to --package, the project already has a command, image-classifier, which runs the main function you replaced in Step 5. Give it a file of its own, src/image_classifier/cli.py, with a download command. First, what the command accepts:

src/image_classifier/cli.py (the arguments)
"""The image-classifier command."""

import argparse
from pathlib import Path


def main() -> None:
parser = argparse.ArgumentParser(
prog="image-classifier", description="Train and use a flower photo classifier."
)
commands = parser.add_subparsers(dest="command", required=True)
download = commands.add_parser("download", help="download the flower photos and count them")
download.add_argument(
"--data-dir",
type=Path,
default=Path("data"),
help="where to keep the photos (default: data)",
)
args = parser.parse_args()
  • argparse, Python's own command-line parser, reads what you type after image-classifier.
  • add_subparsers lets the command have commands of its own, the way git has git commit, and required=True makes naming one compulsory. This part adds download; later parts add commands to train and use the model.
  • --data-dir is optional. It defaults to a data folder in the project, and type=Path turns what you type into a path.

Then what download does:

src/image_classifier/cli.py (the download)
# TensorFlow takes a few seconds to import, so import it only once the arguments are valid.
from image_classifier.data import count_photos, download_photos

photos_dir = download_photos(args.data_dir)
counts = count_photos(photos_dir)
print(f"Photos in {photos_dir}:")
for name, count in counts.items():
print(f" {name:<12}{count:>6,}")
print(f" {'total':<12}{sum(counts.values()):>6,}")
  • The import of data.py, which imports Keras and TensorFlow, sits inside main, after parse_args(). So --help or a mistyped argument answers at once instead of waiting for TensorFlow: --help took 0.05 seconds here.
  • The print lines show each class with its count. :<12 pads the name to 12 characters, and :>6, right-aligns the count in 6 characters with a thousands separator, so the columns line up.

The complete file:

src/image_classifier/cli.py
"""The image-classifier command."""

import argparse
from pathlib import Path


def main() -> None:
parser = argparse.ArgumentParser(
prog="image-classifier", description="Train and use a flower photo classifier."
)
commands = parser.add_subparsers(dest="command", required=True)
download = commands.add_parser("download", help="download the flower photos and count them")
download.add_argument(
"--data-dir",
type=Path,
default=Path("data"),
help="where to keep the photos (default: data)",
)
args = parser.parse_args()

# TensorFlow takes a few seconds to import, so import it only once the arguments are valid.
from image_classifier.data import count_photos, download_photos

photos_dir = download_photos(args.data_dir)
counts = count_photos(photos_dir)
print(f"Photos in {photos_dir}:")
for name, count in counts.items():
print(f" {name:<12}{count:>6,}")
print(f" {'total':<12}{sum(counts.values()):>6,}")

The complete src/image_classifier/cli.py in a macOS-style code window: main builds an argparse parser with a download command and a --data-dir option, imports the data module only after parsing, downloads and counts the photos, and prints each class with its count and the total.

Now point the command at the new function. In pyproject.toml, [project.scripts] still names image_classifier:main, the function Step 5 removed. Change it:

pyproject.toml (project.scripts)
[project.scripts]
image-classifier = "image_classifier.cli:main"

image_classifier.cli:main means the main function in image_classifier/cli.py. How to Add a Command to a Python Project with project.scripts explains the table. While you're in the file, replace uv's placeholder description, "Add your description here", with one of your own. The complete file:

pyproject.toml
[project]
name = "image-classifier"
version = "0.1.0"
description = "Train a flower photo classifier with TensorFlow and Keras."
readme = "README.md"
authors = [
{ name = "Your Name", email = "you@example.com" }
]
requires-python = ">=3.14"
dependencies = [
"tensorflow>=2.22.0",
]

[project.scripts]
image-classifier = "image_classifier.cli:main"

[build-system]
requires = ["uv_build>=0.13.10,<0.14.0"]
build-backend = "uv_build"

The complete pyproject.toml in a macOS-style code window: the image-classifier project on Python 3.14 or later with tensorflow 2.22.0 or later as its dependency, the image-classifier command pointing at image_classifier.cli, and uv_build as the build backend.

authors holds your own name and email, which uv takes from your Git settings: the file above shows placeholders.

Step 8: Download the Photos​

Check the command first:

Terminal
uv run image-classifier --help
Output
Built image-classifier @ file:///Users/you/source/dewiride-image-classifier
Uninstalled 1 package in 1ms
Installed 1 package in 3ms
usage: image-classifier [-h] {download} ...

Train and use a flower photo classifier.

positional arguments:
{download}
download download the flower photos and count them

options:
-h, --help show this help message and exit

The terminal after uv run image-classifier --help: uv rebuilt and reinstalled the project, then the help showed usage: image-classifier with one command, download, to download the flower photos and count them.

The first three lines are uv's. pyproject.toml changed, and uv's settings reference says it rebuilds a project "whenever the pyproject.toml, setup.py, or setup.cfg files in the project directory are modified", so uv run rebuilt and reinstalled the project before running the command. Then argparse printed the help, with download as the only command. Run it:

Terminal
uv run image-classifier download
Output
Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz
228813984/228813984 ━━━━━━━━━━━━━━━━━━━━ 20s 0us/step
Photos in /Users/you/source/dewiride-image-classifier/data/flowers/flower_photos:
daisy 633
dandelion 898
roses 641
sunflowers 699
tulips 799
total 3,670

The terminal after uv run image-classifier download: Keras downloaded flower_photos.tgz, 228813984 bytes in 20 seconds, and the command counted the photos in data/flowers/flower_photos: daisy 633, dandelion 898, roses 641, sunflowers 699 and tulips 799, 3,670 in total.

  • Downloading data from and the progress bar come from get_file: 228,813,984 bytes, the size TensorFlow Datasets publishes, in 20 seconds here.
  • The counts: 3,670 photos in five classes, the same total TensorFlow's tutorial reports: "There are 3,670 total images". The classes aren't the same size: dandelions have the most photos, 898, and daisies the fewest, 633. Keep that in mind, because it matters when Part 10 measures the model.

Run it again:

Terminal
uv run image-classifier download
Output
Photos in /Users/you/source/dewiride-image-classifier/data/flowers/flower_photos:
daisy 633
dandelion 898
roses 641
sunflowers 699
tulips 799
total 3,670

No download this time: get_file found the archive in data, checked it against the hash, and unpacked it again. It took about 5 seconds.

Step 9: Look at the Photos and Their License​

Here's one photo from each class, with how many photos its folder holds:

One photo from each of the five class folders in data/flowers/flower_photos: a daisy with 633 photos, a dandelion with 898, roses with 641, sunflowers with 699 and tulips with 799, each credited to its photographer under CC BY 2.0, 3,670 photos in 5 folders in all.

Photos, left to right and top to bottom: 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, shown smaller than the originals.

The folder names, daisy, dandelion, roses, sunflowers and tulips, are the labels the model will learn to give. The photos come in different sizes, which Part 4 deals with.

The photos have owners, and a license that says how you may use them. It's in LICENSE.txt, next to the folders. Show its first lines:

Terminal
head -n 6 data/flowers/flower_photos/LICENSE.txt
Output
All images in this archive are licensed under the Creative Commons By-Attribution License, available at:
https://creativecommons.org/licenses/by/2.0/
The photographers are listed below, thanks to all of them for making their work available, and please be sure to credit them for any use as per the license.

daisy/7568630428_8cf0fc16ff_n.jpg CC-BY by A Guy Taking Pictures - https://www.flickr.com/photos/80901381@N04/7568630428/
daisy/7410356270_9dff4d0e2e_n.jpg CC-BY by martinak15 - https://www.flickr.com/photos/martinaphotography/7410356270/

The terminal after showing the first six lines of LICENSE.txt: all images are licensed under the Creative Commons By-Attribution License at creativecommons.org/licenses/by/2.0, a request to credit the photographers, and the first two daisy photos with their photographers and Flickr pages.

Every photo is under CC BY 2.0, and the rest of the file lists each photo with its photographer and its Flickr page. The license's summary lets you "copy and redistribute" and "remix, transform, and build upon the material for any purpose, even commercially". Its main condition: "You must give appropriate credit, provide a link to the license, and indicate if changes were made." That's why every flower photo in this series is shown with its credit.

Step 10: Keep the Photos Out of Git and Commit​

The photos are 450 MB that the download command can fetch again at any time, so they don't belong in Git. A .gitignore file lists what Git leaves out, one pattern per line, and uv's already keeps .venv out. At the end of it, add a blank line and then these two lines:

.gitignore (the end)
# Downloaded photos
data/

The complete file:

.gitignore
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info

# Virtual environments
.venv

# Downloaded photos
data/

A line that starts with # is a comment. uv's lines leave out Python's compiled files (__pycache__/, *.py[oc]), what building a package leaves behind (build/, dist/, wheels/, *.egg-info) and the virtual environment (.venv). The new data/ line leaves out every folder named data, with everything in it. How to Ignore a Folder in Git with .gitignore shows what the slashes in a pattern change.

Then check what Git would commit:

Terminal
git status
Output
On branch main

No commits yet

Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
.python-version
README.md
pyproject.toml
src/
uv.lock

nothing added to commit but untracked files present (use "git add" to track)

No data folder in the list: Git ignores it. Commit the rest:

Terminal
git add .
git commit -m "Set up TensorFlow and download the flower photos"
Output
[main (root-commit) fbace49] Set up TensorFlow and download the flower photos
8 files changed, 749 insertions(+)
create mode 100644 .gitignore
create mode 100644 .python-version
create mode 100644 README.md
create mode 100644 pyproject.toml
create mode 100644 src/image_classifier/__init__.py
create mode 100644 src/image_classifier/cli.py
create mode 100644 src/image_classifier/data.py
create mode 100644 uv.lock

The terminal after git status and git commit: the untracked files .gitignore, .python-version, README.md, pyproject.toml, src and uv.lock, then the root commit on main, Set up TensorFlow and download the flower photos, with 8 files.

How to Create a Git Repository and Make Your First Commit covers git add and git commit.

Your Project Now Looks Like This​

dewiride-image-classifier/
dewiride-image-classifier/
├── .gitignore
├── .python-version
├── README.md
├── data/
│ ├── flowers/
│ │ └── flower_photos/
│ │ ├── LICENSE.txt
│ │ ├── daisy/
│ │ ├── dandelion/
│ │ ├── roses/
│ │ ├── sunflowers/
│ │ └── tulips/
│ └── flowers_archive
├── pyproject.toml
├── src/
│ └── image_classifier/
│ ├── __init__.py
│ ├── cli.py
│ └── data.py
└── uv.lock

The tree leaves out three folders that are there too: .venv, .git, where Git keeps the project's history, and src/image_classifier/__pycache__/, where Python keeps a compiled copy of each module it imports, so it loads faster next time. None of them goes into a commit, and neither does data/.

Common Mistakes​

MistakeWhat happensDo this instead
Creating the project on Python 3.15uv add tensorflow stops: all versions of tensorflow have no wheels with a matching Python version tag (e.g., cp315)Use --python 3.14
Stopping a command during the first import, because it looks stuckNothing is wrong: the first import in a new environment took 46 to 52 seconds here, with nothing on the screenLet it finish: later imports take about 2 seconds
Running uv run image-classifier with no commandimage-classifier: error: the following arguments are required: commandName the command: uv run image-classifier download

Troubleshooting​

SymptomLikely causeFix
error: Failed to spawn: image-classifierYou ran it outside the project folder, where uv can't find the project's commandcd dewiride-image-classifier first
ModuleNotFoundError: No module named 'tensorflow'Python was started without uv run, outside the project's environmentStart it with uv run, in the project folder
The archive downloads a second time, then ValueError: Incomplete or corrupted file detected.The download doesn't match PHOTOS_SHA256: a typo in the hash, or a damaged downloadCopy the hash again exactly as in Step 6, and run the command again

FAQ​

Does TensorFlow work on a Mac with Apple silicon?​

Yes, on its CPU. This series is built on an Apple M1 Pro, where uv add tensorflow installed TensorFlow 2.22.0 straight from PyPI. TensorFlow's install page says "There is currently no official GPU support for MacOS", so it doesn't use the Mac's GPU.

Do I need a GPU for this series?​

No. It's built on a CPU, and each part that trains a model says how long training took. On Linux with an NVIDIA graphics card, or on Windows through WSL2, TensorFlow can use a GPU: the install page explains how, and this series hasn't tested it.

Is TensorFlow free to use?​

TensorFlow and Keras are open-source software under the Apache License 2.0, as their PyPI pages show. The flower photos come with their own license, CC BY 2.0, which asks for credit (Step 9).

Clean Up​

Nothing runs in the background, so there's nothing to stop, and Step 3 already deleted imports.txt. Keep the project and the photos: Part 2 starts from both.

Conclusion​

You created a Python 3.14 project with uv, installed TensorFlow 2.22.0 and Keras 3.15.1, and checked that TensorFlow works, on this Mac's CPU. You found where the slow first import goes, and that bytecode isn't the reason. And the project has a download command that fetches 3,670 flower photos, checks the archive's SHA-256, and counts the photos in each of the five classes.

In Part 2 you'll meet the tensor, the data type everything in TensorFlow is built on, and turn these photos into tensors.

Additional Resources​


Next → Part 2: Tensors: Shapes, Data Types and Operations (coming soon)