PyTorch and TensorFlow (with its high-level API Keras) are the two main deep-learning frameworks. Both are free, run on GPUs and can build any modern network. This guide compares them and shows the same model in each.
What You Will Learn
- Key differences in style and ecosystem
- The same classifier in Keras and PyTorch
- Deployment options
- Which one to learn first
Comparison
| PyTorch | TensorFlow / Keras | |
|---|---|---|
| Made by | Meta (now PyTorch Foundation) | |
| Style | Pythonic, explicit training loop | High-level model.fit(); lower-level APIs available |
| Research | Dominant in papers and new models | Less common in new research |
| LLMs & Hugging Face | Primary framework | Supported, but fewer new models |
| Beginner speed | Slightly more code | Very quick with Keras |
| Mobile / browser | ExecuTorch, ONNX | TensorFlow Lite (LiteRT), TensorFlow.js |
| Production serving | TorchServe, ONNX Runtime, Triton | TensorFlow Serving, Vertex AI |
| Multi-backend | – | Keras 3 can run on TensorFlow, JAX or PyTorch |
Same Model in Keras
from tensorflow import keras
(x_tr, y_tr), (x_te, y_te) = keras.datasets.mnist.load_data()
x_tr, x_te = x_tr / 255.0, x_te / 255.0
model = keras.Sequential([
keras.Input(shape=(28, 28)),
keras.layers.Flatten(),
keras.layers.Dense(128, activation="relu"),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation="softmax")])
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_tr, y_tr, epochs=5, validation_split=0.1)
print(model.evaluate(x_te, y_te))
Same Model in PyTorch
import torch, torch.nn as nn
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
tf = transforms.ToTensor()
train = DataLoader(datasets.MNIST(".", train=True, download=True, transform=tf), batch_size=64, shuffle=True)
test = DataLoader(datasets.MNIST(".", train=False, download=True, transform=tf), batch_size=1000)
model = nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Dropout(0.2), nn.Linear(128, 10))
opt = torch.optim.Adam(model.parameters())
loss_fn = nn.CrossEntropyLoss() # includes softmax
for epoch in range(5):
model.train()
for x, y in train:
opt.zero_grad()
loss = loss_fn(model(x), y)
loss.backward()
opt.step()
model.eval(); correct = 0
with torch.no_grad():
for x, y in test:
correct += (model(x).argmax(1) == y).sum().item()
print(correct / len(test.dataset))
Explanation: Both build the same network (784 → 128 → 10) and usually reach about 97–98% test accuracy on MNIST. Keras hides the training loop inside fit(); PyTorch makes you write it, which takes more lines but gives full control – useful for research, GANs and custom training such as fine-tuning LLMs.
Concept Mapping
| Concept | Keras | PyTorch |
|---|---|---|
| Dense layer | layers.Dense(128) | nn.Linear(in, 128) |
| Train | model.fit() | Manual loop: zero_grad → loss → backward → step |
| Train/eval mode | Automatic | model.train() / model.eval() |
| Save | model.save(“m.keras”) | torch.save(model.state_dict(), “m.pt”) |
| GPU | Automatic if available | model.to(“cuda”), x.to(“cuda”) |
Which Should You Learn?
- Want LLMs, research, Hugging Face or computer-vision papers? Learn PyTorch.
- Want the fastest start or mobile/web deployment? Keras is excellent – and with Keras 3 you can switch to a PyTorch backend later.
- Concepts (layers, loss functions, optimizers, backpropagation) transfer completely, so switching later is easy.
Series
Deep learning series: Intro to DL · ANN · Activation Functions · Loss Functions · Backpropagation · Optimizers · Dropout & BatchNorm · CNN · RNN · LSTM & GRU · Transfer Learning · Autoencoders · GANs · PyTorch vs TensorFlow
Interview Questions
Q: Main difference between PyTorch and Keras?
Keras offers a high-level fit() API; PyTorch uses an explicit, Pythonic training loop with more control.
Q: Why call model.eval() in PyTorch?
To switch dropout and batch normalization to inference behaviour.
Practice Exercises
- Run both versions in Google Colab and compare training time and accuracy.
- Add a second hidden layer of 64 units in both frameworks.
Summary
Keras is the quickest way to build and train; PyTorch dominates research and LLM work. The concepts are identical, so pick one, learn it well and pick up the other as needed.
Machine Learning Tutorials, Courses and Certifications