TensorFlow vs Keras vs PyTorch in 2027: One Deep Learning Model Built Three Ways

Adeel's profile picture
Adeel AslamLast Updated on
12-13 Min Read TimeAdd as preferred on Google

Key Takeaways

Our view is that most beginners should learn Keras 3 first, then write the same model's training loop in PyTorch, unless their team already uses one framework.

  • TensorFlow and Keras share one compile-and-fit workflow, while PyTorch has you write the training loop yourself.
  • Keras 3 is a multi-backend framework that trains on JAX, TensorFlow or PyTorch, so the same Sequential model can run on a PyTorch backend after one environment variable change.
  • Python 3.11, 3.12 or 3.13 works with all three frameworks as of November 2026.
  • Python 3.10 still installs TensorFlow but is below the floor for current Keras and PyTorch. Stable TensorFlow 2.21 has no Python 3.14 build, though PyTorch 2.15 lists it.
  • A PyTorch classifier should end without a softmax layer, because nn.CrossEntropyLoss expects raw logits and a second softmax weakens training.
  • Teams whose codebase or engineers already use one framework should stay with it, because that beats any general ranking.

Before choosing a framework, settle the dataset, the success metric and where the model will run.

Most TensorFlow vs Keras vs PyTorch comparisons list adjectives, which tells a beginner little about the code they will actually write. This guide builds the same small classifier in each framework: a two-layer network that sorts 4-feature inputs into 3 classes, using releases current as of November 2026 (TensorFlow 2.21, Keras 3.15 and PyTorch 2.15). TensorFlow and Keras share one workflow, compile and then fit. PyTorch has you write the training loop yourself, and Keras 3 can now run on top of PyTorch.


How does Keras 3 relate to TensorFlow and PyTorch?

Keras 3 is a separate, multi-backend framework that also ships with TensorFlow. It trains models on JAX, TensorFlow or PyTorch, and it can also run predictions on an inference-only OpenVINO backend. According to the Keras migration guide, pip install tensorflow installs Keras 3 from TensorFlow 2.16 onward, and tf.keras then points to Keras 3 by default.


Two practical consequences follow. Keras code is no longer tied to TensorFlow, because the same Sequential model can train on a PyTorch backend after you change one environment variable. Keras also has its own Python floor of 3.11, which is stricter than TensorFlow's. Older tutorials written for Keras 2 still run through the legacy tf_keras package.


Which Python version works for TensorFlow, Keras and PyTorch?

Python 3.11, 3.12 or 3.13 works with all three frameworks as of November 2026. Each project sets its own range:


  • TensorFlow 2.21, the latest stable release (March 2026), dropped Python 3.9, and TensorFlow's pip install guide gives 3.10 to 3.13 as the supported range.
  • Keras 3 requires Python 3.11 or newer.
  • PyTorch 2.15, released in October 2026, requires Python 3.11 or later, and PyTorch's PyPI listing names 3.11 to 3.15.


Two details catch people following older setup guides. Python 3.10 still installs TensorFlow but falls below the floor for current Keras and PyTorch releases. PyTorch 2.15 lists Python 3.14, yet stable TensorFlow 2.21 has no build for it.


For 2027 planning, the overlap is likely to widen. A TensorFlow 2.22 release candidate published in September 2026 adds Python 3.14 support, though no stable 2.22 had shipped when this guide was updated. Pin 3.12 for now. Support ranges move with each release, so check the install pages again before you upgrade Python in a project.


Setting up a virtual environment for deep learning in Python

A virtual environment keeps each project's framework versions apart, so a TensorFlow upgrade in one project cannot break another. Create one with a supported Python version, activate it, then install the frameworks.

# macOS and Linux
python3.12 -m venv dl-env
source dl-env/bin/activate

# Windows (uses the Python launcher)
py -3.12 -m venv dl-env
dl-env\Scripts\activate

# Both platforms
python -m pip install --upgrade pip
pip install numpy tensorflow torch

The prompt shows (dl-env) while the environment is active. deactivate returns you to the system Python. Keras 3 needs no separate install because TensorFlow pulls it in, and pip install --upgrade keras fetches the newest Keras release if you want it. One line confirms all three imports work:

python -c "import tensorflow as tf, keras, torch; print(tf.__version__, keras.__version__, torch.__version__)"

These commands cover CPU learning setups, and GPU drivers and CUDA builds are outside this guide. One Windows note matters, though. TensorFlow 2.10 was the last release with native Windows GPU support, so GPU training with TensorFlow on Windows goes through WSL2.


The example model used in all three frameworks

Every framework below builds the same network: 4 inputs, a hidden layer of 16 units with ReLU, and an output layer of 3 units, trained for 5 epochs in batches of 8 with the Adam optimizer. The data is random, which lets the code run without downloads.

import numpy as np

rng = np.random.default_rng(seed=42)
X_train = rng.random((100, 4), dtype=np.float32)
y_train = rng.integers(0, 3, size=100)
X_test = rng.random((20, 4), dtype=np.float32)
y_test = rng.integers(0, 3, size=20)

The labels have no relationship to the inputs. Expect accuracy near chance level, which is what a model with 3 classes and no signal in the labels produces. To check the training mechanics on real data, swap in a small labelled dataset such as Iris (4 features, 3 classes) and keep the rest of the code.


Building the model in TensorFlow with tf.keras

TensorFlow's standard route for a simple network is its bundled Keras API, tf.keras. You describe the layers and compile the model with an optimizer and a loss. Then fit runs batching, backpropagation, metric tracking and the progress log for you.

Create tensors and check the TensorFlow version

A tensor is TensorFlow's multi-dimensional array. tf.constant creates one from a Python list or NumPy array.

import tensorflow as tf

print(tf.__version__)
a = tf.constant([[1.0, 2.0], [3.0, 4.0]])
print(a.shape, a.dtype)  # (2, 2) <dtype: 'float32'>

Training rarely needs hand-built tensors. model.fit accepts the NumPy arrays from the shared example directly.

Build a Sequential model in TensorFlow

A Sequential model stacks layers in order. The input shape goes in a separate Input object placed first.

model = tf.keras.Sequential([
    tf.keras.Input(shape=(4,)),
    tf.keras.layers.Dense(16, activation="relu"),
    tf.keras.layers.Dense(3, activation="softmax"),
])
model.summary()

Many older tutorials pass input_shape=(4,) to the first Dense layer. Keras 3 prints a warning for that pattern ("Do not pass an input_shape/input_dim argument to a layer") and recommends an Input(shape) object as the first item in a Sequential model, which is why this version may differ from code you copied before.

Train and evaluate with compile and fit

compile attaches the optimizer, loss and metrics. fit trains, and evaluate scores the model on held-out data.

model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"],
)
model.fit(X_train, y_train, epochs=5, batch_size=8)

loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test loss {loss:.4f}, accuracy {accuracy:.2f}")

The "sparse" loss takes integer labels (0, 1, 2) without one-hot encoding. It pairs with the softmax output layer, which turns the final scores into probabilities.

Predict classes with TensorFlow

predict returns one probability per class for each input row. The index of the largest value is the predicted class.

probs = model.predict(X_test[:5])
print(probs.round(3))
print(probs.argmax(axis=1))

Running the same model in standalone Keras 3

Standalone Keras 3 uses the same model code as tf.keras. Only the import and the backend choice change. The example below runs on PyTorch to show that the Keras workflow does not depend on TensorFlow at all.

Select a backend and check the Keras version

Keras reads the KERAS_BACKEND environment variable. The training backends are "jax", "tensorflow" and "torch", with "openvino" available for inference only. Set the variable before importing Keras, because the backend cannot change after the import.

import os
os.environ["KERAS_BACKEND"] = "torch"

import keras
print(keras.__version__, keras.config.backend())  # e.g. 3.15.1 torch

A machine-wide default can live in ~/.keras/keras.json instead.

Build a Keras Sequential model example

model = keras.Sequential([
    keras.Input(shape=(4,)),
    keras.layers.Dense(16, activation="relu"),
    keras.layers.Dense(3, activation="softmax"),
])

Apart from the keras. prefix in place of tf.keras., the model matches the TensorFlow version line for line.

Train and evaluate on the PyTorch backend

model.compile(optimizer="adam",
              loss="sparse_categorical_crossentropy",
              metrics=["accuracy"])
model.fit(X_train, y_train, epochs=5, batch_size=8)
loss, accuracy = model.evaluate(X_test, y_test)

The calls and arguments are identical to TensorFlow's. Keras still accepts NumPy arrays, and PyTorch does the tensor work underneath.

Predict classes with Keras

probs = model.predict(X_test[:5])
print(probs.argmax(axis=1))

Switching backends this way is handy for learning. Real projects should pick one backend and stay on it, because a custom layer that calls tf.* or torch.* functions directly only runs on the backend it was written for.


Implementing the neural network in PyTorch

PyTorch has no compile-and-fit step for this kind of model. You define the model, the loss function and the optimizer as separate objects, then write the loop that feeds batches, computes the loss, runs backpropagation and updates the weights. That costs more lines. In return, every step of training is visible and open to change.

Create tensors and check the PyTorch version

import torch

print(torch.__version__)
a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print(a.shape, a.dtype)  # torch.Size([2, 2]) torch.float32

PyTorch models expect tensors, so the NumPy example data needs converting first. torch.from_numpy does that without copying the data.

Build the model with nn.Sequential

from torch import nn

torch.manual_seed(42)
model = nn.Sequential(
    nn.Linear(4, 16),
    nn.ReLU(),
    nn.Linear(16, 3),  # raw scores (logits), no softmax
)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters())

nn.Sequential takes the layers as separate positional arguments (or one OrderedDict). Wrapping them in a Python list, as Keras code does, raises an error, and it is a common copy-paste slip. The model also ends without a softmax layer. nn.CrossEntropyLoss expects unnormalized logits for each class, so adding nn.Softmax before it squashes the scores twice and weakens training.

Train and evaluate with a PyTorch training loop

A DataLoader wraps the tensors and returns shuffled batches of 8, matching the Keras batch_size.

from torch.utils.data import DataLoader, TensorDataset

X_train_t = torch.from_numpy(X_train)
y_train_t = torch.from_numpy(y_train).long()
loader = DataLoader(TensorDataset(X_train_t, y_train_t),
                    batch_size=8, shuffle=True)

for epoch in range(5):
    model.train()
    total_loss = 0.0
    for xb, yb in loader:
        optimizer.zero_grad()          # clear old gradients
        loss = loss_fn(model(xb), yb)  # forward pass
        loss.backward()                # backpropagation
        optimizer.step()               # update weights
        total_loss += loss.item() * len(xb)
    print(f"Epoch {epoch + 1}, loss {total_loss / len(loader.dataset):.4f}")

X_test_t = torch.from_numpy(X_test)
y_test_t = torch.from_numpy(y_test).long()
model.eval()
with torch.no_grad():
    logits = model(X_test_t)
    test_loss = loss_fn(logits, y_test_t).item()
    accuracy = (logits.argmax(dim=1) == y_test_t).float().mean().item()
print(f"Test loss {test_loss:.4f}, accuracy {accuracy:.2f}")

The four lines inside the batch loop are the steps that Keras's fit hides. model.train() and model.eval() switch layers such as Dropout and BatchNorm between training and evaluation behaviour; this model has neither, but the habit prevents confusing bugs once you add them. torch.no_grad() stops gradient tracking during evaluation.

Predict classes with PyTorch

Calling the model on a tensor returns logits. Apply torch.softmax when you need probabilities.

with torch.no_grad():
    probs = torch.softmax(model(X_test_t[:5]), dim=1)
print(probs.argmax(dim=1))

The predicted classes come out the same with or without softmax, because softmax never changes which score is largest.


TensorFlow vs Keras vs PyTorch side by side

TensorFlow and Keras 3 share one model-building and training API. PyTorch differs mainly at training time, where the loop is your own code. The table compares the three as used in this guide, with versions as of November 2026.

FrameworkInstallPythonBuild the modelTrain and evaluatePredict returnsBest for
TensorFlow 2.21 (tf.keras)pip install tensorflow (includes Keras 3)3.10 to 3.13tf.keras.Sequential([Input, ...])compile, fit, evaluateProbabilitiesTeams already on the TensorFlow toolchain
Keras 3.15 (standalone)pip install keras plus a backend3.11 or newerkeras.Sequential([Input, ...])compile, fit, evaluateProbabilitiesLearning concepts fast and keeping the backend choice open
PyTorch 2.15pip install torch3.11 or laternn.Sequential(layer, layer, ...)Hand-written loop over a DataLoader, then model.eval() with torch.no_grad()LogitsSeeing what training does step by step, and custom training logic

Which deep learning framework should you learn first?

Our view is that most beginners should start with Keras 3, then learn PyTorch's training loop, and pick up TensorFlow-specific tooling when a project calls for it. Keras builds and trains the example model in about ten lines. That puts the first week into concepts (layers, loss, epochs, overfitting) instead of loop mechanics.


The recommendation shifts with the reader's goal:


  • A student or career switcher should start with Keras, then rewrite the same model in PyTorch. Seeing fit broken into zero_grad, backward and step is where training starts to make sense.
  • A backend engineer joining a team should learn whatever the team's codebase already uses. Keras 3's PyTorch backend lets a Keras learner contribute to a PyTorch stack on day one.
  • A tech lead scoping a prototype should choose by the team's existing skills and the deployment target. Framework choice is a small part of the schedule, and our guide on how long it takes to build and deploy a machine learning model covers where the time actually goes.


The concepts carry across. Tensors, layers, a loss function, an optimizer, batches and an evaluation set appear in all three frameworks, so time spent on one shortens the second.


None of the code here is production-ready. It skips input validation, real data splits, checkpointing and reproducibility settings. Treat it as a map of the APIs.


Frequently asked questions

Can input_shape still be used in a Keras Dense layer?

It still runs, but Keras 3 warns against passing input_shape or input_dim to a layer. Put keras.Input(shape=(4,)) first in the Sequential model and add Dense layers without a shape argument. That one-line change brings older tutorial code in line with current Keras guidance.

Why does a PyTorch classifier not need a softmax layer?

nn.CrossEntropyLoss expects raw, unnormalized logits for each class and handles the softmax step itself. Adding nn.Softmax at the end of the model applies it twice and weakens the training signal. Keep the final Linear layer as the output, and call torch.softmax only at prediction time when you need probabilities.

Do Keras 2 tutorials still work with TensorFlow 2.16 or later?

Yes, with one change. TensorFlow 2.16 and later install Keras 3 by default. Install the tf_keras package and import it as keras, or set TF_USE_LEGACY_KERAS=1 before importing TensorFlow so tf.keras points back to Keras 2.

Why is accuracy stuck near chance level in this example?

The example data is random. Its labels carry no pattern, so accuracy near chance level is the expected result and shows the code runs correctly. Swap in a real labelled dataset such as Iris to watch accuracy rise over the epochs.

Can one Python environment hold TensorFlow, Keras and PyTorch together?

Yes, on Python 3.11 to 3.13 as of November 2026. Python 3.10 falls below the minimum for current Keras and PyTorch releases, and Python 3.14 has no stable TensorFlow build yet.


Planning your first neural network prototype

For most people weighing TensorFlow vs Keras vs PyTorch, the practical order is Keras 3 first to get a model training quickly, then the same model in PyTorch so the training loop stops being a black box. The main qualification is your team. If your codebase or engineers already use one framework, that one beats any general ranking. Before writing model code for a real product, settle the dataset, the metric that defines success and where the model will run, because those choices shape the framework decision more than API style does. If you are scoping an ML prototype for 2027 and want engineers who build in both TensorFlow and PyTorch, talk to Arbisoft's AI and machine learning development team.

...Loading Related Blogs

Explore More

From Introduction to Proposal in Days

Discovery Call
Our sales team reviews your message and asks for a discovery call to gather more information.
Expert Input
Our veterans go through your requirements to provide their take, backed by decades of experience.
Proposal
We provide a proposal specific to what you're building, for you to review at your own pace.

Trusted by top platforms for our transformative solutions and exceptional results:

How Can We Help You Build?

We recommend using your work email.
We'll send a mutual NDA before the discovery call if requested. Zero obligation.