Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

TensorFlow classification follows a repeatable workflow: define the labels, prepare representative data, build an input pipeline, match the model output and loss to the label format, train with validation, evaluate on an untouched test set, inspect errors, and save a reproducible inference procedure. This guide uses multiclass image classification as the main example, then shows how the same decisions change for binary, multilabel, tabular, and text problems.

You can run the examples in Google Colab or locally. The official installation page identified TensorFlow 2.21.0 as the latest stable release on March 12, 2026; check the live installation instructions for current Python and platform compatibility.

What classification means

A classification model predicts a discrete label, not a continuous number. Binary classification chooses between two classes such as spam and not spam. Multiclass classification chooses one class from several, such as cat, dog, or bird. Multilabel classification allows several labels to be true for one example, such as an image containing both a person and a dog.

A neural network’s final values are usually logits. Applying softmax converts multiclass logits into values that sum to one, called probabilities; the largest value gives the predicted class. A high softmax value is not automatically a trustworthy probability: calibration, data quality, and distribution shift still matter.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Prerequisites and setup

  • Basic Python, functions, imports, and simple NumPy operations.
  • Familiarity with features, labels, batches, epochs, loss, and accuracy.
  • A notebook or command-line Python environment.

For the least setup, open a TensorFlow tutorial and choose Run in Google Colab, connect to a runtime, then use Runtime → Run all. A local virtual environment is better when you need persistent files and reproducible development.

Local CPU installation

python3 -m venv tf
source tf/bin/activate
python -m pip install --upgrade pip
python -m pip install tensorflow
python -c "import tensorflow as tf; print(tf.__version__)"

On Linux, the current guide documents this GPU installation command:

python3 -m pip install 'tensorflow[and-cuda]'
python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"

Small datasets do not require a GPU. Native-Windows official GPU support ends with TensorFlow 2.10; newer GPU workflows generally use WSL2 or another supported environment. Verify platform details at TensorFlow’s installation guide.

The end-to-end workflow

  1. Define classes and the prediction target.
  2. Collect, label, inspect, and split representative data.
  3. Load and preprocess it consistently.
  4. Choose output units, loss, optimizer, and metrics that match the labels.
  5. Train while monitoring validation behavior.
  6. Evaluate once on an untouched test set and inspect errors.
  7. Save the model, class ordering, and preprocessing assumptions.

Choose and organize an image dataset

For a directory-based project, use one subdirectory per class:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
dataset/
├── cats/
│   ├── cat_001.jpg
│   └── cat_002.jpg
├── dogs/
│   ├── dog_001.jpg
│   └── dog_002.jpg
└── birds/
    ├── bird_001.jpg
    └── bird_002.jpg

TensorFlow’s image tutorial uses image_dataset_from_directory, which infers integer class IDs from subdirectory names.

  • Keep names stable and unambiguous; save their ordering with the model.
  • Remove corrupt, mislabeled, duplicate, and near-duplicate files.
  • Use images resembling the real lighting, devices, backgrounds, and users.
  • Check class counts. If related images come from one person, patient, video, or device, split by that source to prevent leakage.
  • Use validation during development and keep a separate test set untouched until final reporting.

Load, split, and inspect the data

import tensorflow as tf

IMG_HEIGHT = 180
IMG_WIDTH = 180
BATCH_SIZE = 32
SEED = 123

train_ds = tf.keras.utils.image_dataset_from_directory(
    "dataset",
    validation_split=0.2,
    subset="training",
    seed=SEED,
    image_size=(IMG_HEIGHT, IMG_WIDTH),
    batch_size=BATCH_SIZE,
)

val_ds = tf.keras.utils.image_dataset_from_directory(
    "dataset",
    validation_split=0.2,
    subset="validation",
    seed=SEED,
    image_size=(IMG_HEIGHT, IMG_WIDTH),
    batch_size=BATCH_SIZE,
)

print(train_ds.class_names)
for images, labels in train_ds.take(1):
    print(images.shape, labels.shape, labels.dtype)

Use the identical validation fraction and seed in both calls. This creates training and validation subsets, not an independent test set. For serious reporting, create a carefully designed third partition.

Input-pipeline performance

AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

cache() can consume substantial memory; omit it or provide a cache filename when the dataset does not fit in memory.

Build a small convolutional classifier

num_classes = len(train_ds.class_names)

model = tf.keras.Sequential([
    tf.keras.Input(shape=(IMG_HEIGHT, IMG_WIDTH, 3)),
    tf.keras.layers.Rescaling(1.0 / 255),
    tf.keras.layers.Conv2D(16, 3, padding="same", activation="relu"),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Conv2D(32, 3, padding="same", activation="relu"),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Conv2D(64, 3, padding="same", activation="relu"),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation="relu"),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(num_classes),
])
  • Input declares height, width, and three RGB channels.
  • Rescaling changes pixel values from approximately 0–255 to 0–1.
  • Conv2D learns local visual patterns; pooling reduces spatial size.
  • Flatten converts feature maps to a vector for dense layers.
  • Dropout regularizes the dense representation.
  • The final dense layer emits one logit per class and deliberately has no softmax.

Compile with a loss that matches the labels

model.compile(
    optimizer="adam",
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=["accuracy"],
)

Integer class IDs require sparse categorical cross-entropy. With no softmax in the model, from_logits=True lets the loss perform a numerically stable calculation. TensorFlow’s beginner quickstart explains why adding softmax before this loss is unnecessary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Task Labels Output Typical loss
Binary 0/1 One sigmoid unit Binary cross-entropy
Binary 0/1 Two logits Sparse categorical cross-entropy
Multiclass Integer class ID One logit per class Sparse categorical cross-entropy with from_logits=True
Multiclass One-hot vector One logit per class Categorical cross-entropy
Multilabel 0/1 vector One sigmoid unit per label Binary cross-entropy

Do not mix integer labels with a loss expecting one-hot vectors, one-hot labels with sparse loss, or from_logits=True with a model that already applies softmax.

Train with validation and callbacks

callbacks = [
    tf.keras.callbacks.EarlyStopping(
        monitor="val_loss", patience=3, restore_best_weights=True
    ),
    tf.keras.callbacks.ModelCheckpoint(
        "best_model.keras", monitor="val_accuracy",
        mode="max", save_best_only=True
    ),
]

history = model.fit(
    train_ds,
    validation_data=val_ds,
    epochs=30,
    callbacks=callbacks,
)

An epoch is one pass through the training data; a batch is the group processed in one step. Training metrics describe data the optimizer has seen. Validation metrics estimate performance on held-out data and guide decisions, so they are not a substitute for a final test.

Recognize and reduce overfitting

Overfitting commonly appears when training accuracy keeps rising while validation accuracy plateaus or falls, or when training loss falls while validation loss rises.

data_augmentation = tf.keras.Sequential([
    tf.keras.layers.RandomFlip("horizontal"),
    tf.keras.layers.RandomRotation(0.1),
    tf.keras.layers.RandomZoom(0.1),
])

Apply random augmentation only to training examples, either in the model or input pipeline. Other remedies include more representative data, removing leakage, a smaller model, dropout, regularization, early stopping, class reweighting, and transfer learning. A from-scratch CNN teaches mechanics but often needs more labeled data; transfer learning is usually stronger on small visual datasets, although base-model preprocessing, fine-tuning, and weight provenance add complexity. TensorFlow’s learning resources cover transfer-learning options at tensorflow.org/learn.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Evaluate beyond accuracy

After development, evaluate exactly once on an untouched test dataset:

test_loss, test_accuracy = model.evaluate(test_ds, verbose=2)
print(test_loss, test_accuracy)

Accuracy is informative when classes are reasonably balanced and error costs are similar. Otherwise inspect precision, recall, F1 score, confusion matrices, per-class results, and (where appropriate) ROC-AUC or PR-AUC. Review false positives, false negatives, low-score cases, and examples with unusual lighting, backgrounds, devices, or demographics.

Report the split method, class balance, preprocessing, random seed, software and hardware environment, and evaluation protocol with any metric. A test score is not evidence of deployment reliability unless the test distribution represents deployment. For safety-sensitive uses, define a confidence threshold below which the system abstains or requests human review.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Save and reload the classifier

model.save("classifier.keras")
restored_model = tf.keras.models.load_model("classifier.keras")

The .keras format stores architecture, weights, training configuration, and optimizer state. A weights-only checkpoint requires recreating the architecture; SavedModel remains useful for TensorFlow Serving and some deployment workflows. See TensorFlow’s save and load guide and the Keras model-format guide. Store class names, image dimensions, channel order, scaling, library versions, and the data-split definition beside the file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Make predictions on a new image

import numpy as np
from tensorflow.keras.utils import load_img, img_to_array

probability_model = tf.keras.Sequential([
    model,
    tf.keras.layers.Softmax()
])

img = load_img("example.jpg", target_size=(IMG_HEIGHT, IMG_WIDTH))
x = img_to_array(img)
x = tf.expand_dims(x, axis=0)
probabilities = probability_model.predict(x, verbose=0)[0]
predicted_index = int(np.argmax(probabilities))
predicted_name = train_ds.class_names[predicted_index]
confidence = float(probabilities[predicted_index])
print(predicted_name, confidence)

The model’s embedded rescaling layer ensures this path uses the same pixel scaling as training. Preserve RGB channels, dimensions, and the exact class-name order. The largest probability is a ranking signal, not proof of correctness.

Troubleshoot common failures

Installation errors

  • Check the Python version against the current installation page and upgrade pip.
  • Use a fresh virtual environment and install with pip.
  • For GPU issues, verify supported operating system, drivers, and TensorFlow release rather than assuming a GPU is available.

Shape or label errors

print(model.input_shape)
for images, labels in train_ds.take(1):
    print(images.shape, labels.shape, labels.dtype)

Typical causes are grayscale images sent to a three-channel model, a missing batch dimension, inconsistent resizing, or labels with the wrong dtype or shape.

High accuracy but bad real predictions

  • Look for leakage, duplicates, class imbalance, mislabeled files, and an unrepresentative test set.
  • Check train–deployment distribution shift and inference preprocessing.
  • Verify that the class-name mapping was saved and restored correctly.

Out-of-memory errors

  • Reduce batch size or image dimensions.
  • Use a smaller model and avoid caching the whole dataset.
  • Stream data and remove unnecessary workers or cached tensors.

Unstable validation accuracy

Inspect validation-set size and class counts, correlated samples, random seeds, augmentation strength, learning rate, and leakage.

Adapt the pattern to other problems

Built-in sanity checks

MNIST or Fashion-MNIST is a fast way to verify that TensorFlow, labels, loss, and training work. The official quickstart uses pixel scaling, a sequential model, dropout, ten output logits, Adam, five epochs, and final test evaluation; those are teaching defaults, not guarantees for other datasets. Start at the beginner quickstart.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Tabular and text classification

Replace image decoding and convolution layers with numeric feature preprocessing or tokenization and embedding layers. The output/loss decision remains the same: one sigmoid for binary output, one sigmoid per independent multilabel target, or one logit per mutually exclusive class.

Deployment choices

  • TensorFlow Lite (also referred to in current materials as LiteRT) for mobile and edge inference.
  • TensorFlow.js for browser inference.
  • TensorFlow Serving for server-side prediction.
  • TFX for production pipelines, validation, and lifecycle management.

TensorFlow lists these environments and managed options in its learning materials, with production pipeline details at tensorflow.org/tfx. Cloud training is documented at TensorFlow Cloud; it adds billing, storage, permissions, and resource-cleanup responsibilities and is unnecessary for a first CPU or Colab experiment.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.