Home Topics TensorFlow & PyTorch

TensorFlow & PyTorch

The two giants of deep learning

15 hours 40 examples Intermediate
Overview

TensorFlow vs PyTorch

These two frameworks dominate modern deep learning. Both can build the same models, but have different philosophies and strengths.

TF

TensorFlow

By Google. Production-focused, excellent deployment tools.

  • ✓ Keras integration - High-level API
  • ✓ TensorFlow Lite - Mobile deployment
  • ✓ TensorFlow.js - Run in browser
  • ✓ TensorBoard - Visualization
  • ✗ Less intuitive debugging
🔥

PyTorch

By Meta/Facebook. Research-focused, more Pythonic.

  • ✓ Dynamic graphs - Debug like Python
  • ✓ Pythonic syntax - More intuitive
  • ✓ Research papers - Preferred by academia
  • ✓ Hugging Face - Primary framework
  • ✗ Deployment less mature
Overview

Which Should You Choose?

Quick Decision Guide

TensorFlow: Production apps, mobile/web deployment, beginners (Keras)
PyTorch: Research, prototyping, NLP (Hugging Face), computer vision
Both: Learn the concepts - skills transfer between frameworks!
TensorFlow

TensorFlow Basics

tf_basics.py
import tensorflow as tf

# Create tensors (multi-dimensional arrays)
scalar = tf.constant(5)                           # 0-D tensor
vector = tf.constant([1, 2, 3])                   # 1-D tensor
matrix = tf.constant([[1, 2], [3, 4]])          # 2-D tensor

print("Scalar:", scalar.numpy())
print("Vector:", vector.numpy())
print("Matrix:\n", matrix.numpy())

# Operations
a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[5, 6], [7, 8]])

print("\nAddition:\n", tf.add(a, b).numpy())
print("Matrix Multiply:\n", tf.matmul(a, b).numpy())
print("Shape:", a.shape)
print("Dtype:", a.dtype)
Output
Scalar: 5
Vector: [1 2 3]
Matrix:
 [[1 2]
 [3 4]]

Addition:
 [[ 6  8]
 [10 12]]
Matrix Multiply:
 [[19 22]
 [43 50]]
Shape: (2, 2)
Dtype: 
TensorFlow

Build Neural Network with Keras

keras_classifier.py
import tensorflow as tf
from tensorflow.keras import layers, models

# Load MNIST handwritten digits
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
X_train, X_test = X_train / 255.0, X_test / 255.0  # Normalize

# Build model (Sequential API - easiest way)
model = models.Sequential([
    layers.Flatten(input_shape=(28, 28)),    # 28x28 → 784
    layers.Dense(128, activation='relu'),     # Hidden layer
    layers.Dropout(0.2),                       # Regularization
    layers.Dense(10, activation='softmax')    # 10 classes
])

# Compile
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

# Train
model.fit(X_train, y_train, epochs=3, validation_split=0.1)

# Evaluate
loss, acc = model.evaluate(X_test, y_test, verbose=0)
print(f"\n🎯 Test Accuracy: {acc*100:.2f}%")
Output
Epoch 1/3 - loss: 0.3021 - accuracy: 0.9132 - val_accuracy: 0.9643
Epoch 2/3 - loss: 0.1459 - accuracy: 0.9574 - val_accuracy: 0.9707
Epoch 3/3 - loss: 0.1087 - accuracy: 0.9675 - val_accuracy: 0.9735

🎯 Test Accuracy: 97.21%
PyTorch

PyTorch Basics

pytorch_basics.py
import torch

# Create tensors
scalar = torch.tensor(5)
vector = torch.tensor([1, 2, 3])
matrix = torch.tensor([[1, 2], [3, 4]])

print("Scalar:", scalar.item())
print("Vector:", vector.numpy())
print("Matrix:\n", matrix.numpy())

# Operations (very similar to NumPy!)
a = torch.tensor([[1., 2.], [3., 4.]])
b = torch.tensor([[5., 6.], [7., 8.]])

print("\nAddition:\n", (a + b).numpy())
print("Matrix Multiply:\n", torch.matmul(a, b).numpy())

# GPU support
if torch.cuda.is_available():
    gpu_tensor = a.cuda()  # Move to GPU
    print("GPU available!")
else:
    print("CPU mode")
Output
Scalar: 5
Vector: [1 2 3]
Matrix:
 [[1 2]
 [3 4]]

Addition:
 [[ 6.  8.]
 [10. 12.]]
Matrix Multiply:
 [[19. 22.]
 [43. 50.]]
CPU mode
PyTorch

Build Neural Network with PyTorch

pytorch_classifier.py
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms

# Define the neural network
class SimpleNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.layers = nn.Sequential(
            nn.Linear(784, 128),   # Input → Hidden
            nn.ReLU(),
            nn.Dropout(0.2),
            nn.Linear(128, 10)     # Hidden → Output
        )
    
    def forward(self, x):
        x = self.flatten(x)
        return self.layers(x)

# Load data
transform = transforms.Compose([transforms.ToTensor()])
train_data = datasets.MNIST('./data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64)

# Initialize
model = SimpleNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())

# Training loop
print("Training...")
model.train()
for epoch in range(3):
    total_loss = 0
    for images, labels in train_loader:
        optimizer.zero_grad()              # Reset gradients
        outputs = model(images)            # Forward pass
        loss = criterion(outputs, labels)  # Calculate loss
        loss.backward()                    # Backpropagation
        optimizer.step()                   # Update weights
        total_loss += loss.item()
    print(f"Epoch {epoch+1}/3 - Loss: {total_loss/len(train_loader):.4f}")

print("✓ Training complete!")
Output
Training...
Epoch 1/3 - Loss: 0.3542
Epoch 2/3 - Loss: 0.1621
Epoch 3/3 - Loss: 0.1198
✓ Training complete!

Key Difference in Training

Keras (TensorFlow)
model.fit(X, y, epochs=3)

One-liner training

PyTorch
Manual training loop

More control, more verbose

🎉 You've Learned Both Frameworks!

Now build more complex architectures: CNNs, RNNs, and Transformers.