ML Libraries

The ML libraries that we’ll be looking at in this lesson are absolute beasts.

They have been under active development for 8+ years, and it’s difficult to imagine how much value they have collectively provided to the world.

This Lesson Will Cover
  • πŸ€– Scikit-learn for traditional machine learning
  • πŸ”₯ TensorFlow for deep learning and production
  • πŸ§ͺ PyTorch for research and experimentation

Scikit-learn

What is Scikit-learn?

Scikit-learn is a powerful Python library for traditional machine learning tasks such as classification, regression, clustering, and preprocessing.

It’s known for its simplicity and comprehensive functionality.

If you’ve been following along from the start of this ML Fundamentals section of this course, then you’re very familiar with Scikit-learn already.

Why use Scikit-learn?

  • Ease of use: Intuitive APIs for all major ML algorithms.
  • Comprehensive toolkit: Includes preprocessing tools, feature selection, and evaluation metrics.
  • Great for beginners: Ideal for learning the fundamentals of ML before diving into deep learning.
Example: Decision Tree Classifier

Here, we train a model using a pipeline and then calculate the accuracy and AUC.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_curve, auc

# Load binary classification dataset
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.3, random_state=42)

# Create pipeline with preprocessing and model
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('classifier', DecisionTreeClassifier(random_state=42, max_depth=2))
])

# Train the pipeline
pipeline.fit(X_train, y_train)

# Get predictions and probabilities
y_pred = pipeline.predict(X_test)
y_pred_proba = pipeline.predict_proba(X_test)[:,1]

# Calculate accuracy
accuracy = pipeline.score(X_test, y_test)
print(f"Accuracy: {accuracy:.2f}")

# Calculate ROC curve and AUC
fpr, tpr, _ = roc_curve(y_test, y_pred_proba)
roc_auc = auc(fpr, tpr)
print(f"AUC: {roc_auc:.2f}")

# Outputs:
# Accuracy: 0.93
# AUC: 0.95
Decision Tree Structure for Breast Cancer Classification
Resulting decision tree structure for breast cancer classification (example above).

TensorFlow

What is TensorFlow?

TensorFlow is an open-source deep learning framework developed by Google.

It supports building and training complex neural networks for a wide range of tasks, from image recognition to natural language processing.

Why use TensorFlow?

  • Versatility: Build models for various devices (CPUs, GPUs, TPUs).
  • Ecosystem: Offers tools like TensorFlow Hub for pre-trained models and TensorFlow Lite for mobile deployment.
  • High-level API: Keras, a TensorFlow library, simplifies model building.
Example: Digit Classification with Neural Networks

Here, we build a neural network to classify handwritten digits using TensorFlow’s Keras API.

Neural Network Architecture Diagram with Sampled Weight Connections - 3 learnable layers and 2 dropout layers
Architecture diagram visualization of the neural networks below (both the TensorFlow and PyTorch examples use this neural network architecture). For the purposes of visualization, only a sample of connections are shown between layers rather than the actual fully-connected structure (or rather, the "mostly connected" structure, when considering the dropout layers which will remove 20% of the node connections).
import tensorflow as tf
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import numpy as np

# Load and preprocess data
digits = load_digits()
X = digits.data.astype('float32') / 16.0  # Normalize data
y = tf.keras.utils.to_categorical(digits.target, 10)  # One-hot encode labels

# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Build the model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(128, activation='relu', input_shape=(64,)),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])

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

# Train the model
history = model.fit(
    X_train,
    y_train,
    batch_size=32,
    epochs=50,
    validation_split=0.2,
    verbose=1,
)

# Evaluate the model
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f'Test accuracy: {test_accuracy:.3f}')

# Make predictions
predictions = model.predict(X_test)
predicted_classes = np.argmax(predictions, axis=1)
print("Sample prediction classes:")
for i in range(15):
    print(f"Prediction: {predicted_classes[i]}, Actual: {np.argmax(y_test[i])}")

Here’s the output:

Epoch 1/50
32/32 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.1682 - loss: 2.2537 - val_accuracy: 0.6429 - val_loss: 1.8672
Epoch 2/50
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.5470 - loss: 1.7558 - val_accuracy: 0.8135 - val_loss: 1.1754
...
Epoch 49/50
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.9954 - loss: 0.0214 - val_accuracy: 0.9444 - val_loss: 0.1378
Epoch 50/50
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.9849 - loss: 0.0376 - val_accuracy: 0.9603 - val_loss: 0.1247
Test accuracy: 0.976
17/17 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step
Sample prediction classes:
Prediction: 6, Actual: 6
Prediction: 9, Actual: 9
Prediction: 3, Actual: 3
Prediction: 7, Actual: 7
Prediction: 2, Actual: 2
Prediction: 1, Actual: 1
Prediction: 5, Actual: 5
Prediction: 2, Actual: 2
Prediction: 5, Actual: 5
Prediction: 2, Actual: 2
Prediction: 1, Actual: 1
Prediction: 9, Actual: 9
Prediction: 4, Actual: 4
Prediction: 0, Actual: 0
Prediction: 4, Actual: 4
Training vs Validation Accuracy of TensorFlow Model
Training and validation-accuracy curves over 50 epochs for the TensorFlow example above.

PyTorch

What is PyTorch?

PyTorch is an open-source deep learning framework developed by Facebook.

It’s known for its dynamic computation graph, which makes it easier to debug and experiment with models.

Why use PyTorch?

  • Flexibility: Dynamic computation graphs allow for adaptive architectures.
  • Community: A large ecosystem of tools and pre-trained models (e.g., Hugging Face Transformers).
  • Popular in research: Preferred for prototyping cutting-edge models.
Example: Digit Classification with Neural Networks

Here, we build a neural network to classify handwritten digits using PyTorch.

As you read through the code below, note how different the PyTorch API is compared to TensorFlow. Both examples accomplish the same task: training a 5-layer neural network to classify handwritten digits.

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import numpy as np

# Load and preprocess data
digits = load_digits()
X = digits.data.astype('float32') / 16.0
y = digits.target

# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Convert to PyTorch tensors and create datasets
train_dataset = TensorDataset(torch.FloatTensor(X_train), torch.LongTensor(y_train))
test_dataset = TensorDataset(torch.FloatTensor(X_test), torch.LongTensor(y_test))

# Split training data for validation (20%)
train_size = int(0.8 * len(train_dataset))
val_size = len(train_dataset) - train_size
train_subset, val_subset = torch.utils.data.random_split(train_dataset, [train_size, val_size])

# Create dataloaders
train_loader = DataLoader(train_subset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_subset, batch_size=32)
test_loader = DataLoader(test_dataset, batch_size=32)

# Define the model
model = nn.Sequential(
    nn.Linear(64, 128),
    nn.ReLU(),
    nn.Dropout(0.2),
    nn.Linear(128, 64),
    nn.ReLU(),
    nn.Dropout(0.2),
    nn.Linear(64, 10)
)

# Define loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())

# Training function
def train_epoch(model, loader, optimizer, criterion):
    model.train()
    running_loss = 0.0
    correct = 0
    total = 0

    for inputs, labels in loader:
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        _, predicted = torch.max(outputs, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    return running_loss/len(loader), correct/total

# Evaluation function
def evaluate(model, loader, criterion):
    model.eval()
    running_loss = 0.0
    correct = 0
    total = 0

    with torch.no_grad():
        for inputs, labels in loader:
            outputs = model(inputs)
            loss = criterion(outputs, labels)
            running_loss += loss.item()
            _, predicted = torch.max(outputs, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

    return running_loss/len(loader), correct/total

# Training loop
for epoch in range(50):
    train_loss, train_acc = train_epoch(model, train_loader, optimizer, criterion)
    val_loss, val_acc = evaluate(model, val_loader, criterion)

    if epoch % 5 == 0 or epoch == 49:  # Print only every 5 epochs to reduce verbosity
        print(f'Epoch {epoch+1}/50, Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.4f}, '
              f'Val Loss: {val_loss:.4f}, Val Acc: {val_acc:.4f}')

# Test the model
test_loss, test_acc = evaluate(model, test_loader, criterion)
print(f'Test accuracy: {test_acc:.3f}')

# Make predictions on test data
model.eval()
predictions = []
true_labels = []

with torch.no_grad():
    for inputs, labels in test_loader:
        outputs = model(inputs)
        _, preds = torch.max(outputs, 1)
        predictions.extend(preds.cpu().numpy())
        true_labels.extend(labels.cpu().numpy())

# Print sample predictions
print("Sample prediction classes:")
for i in range(15):
    print(f"Prediction: {predictions[i]}, Actual: {true_labels[i]}")

Here’s the output:

Epoch 1/50, Train Loss: 2.2110, Train Acc: 0.2876, Val Loss: 2.0519, Val Acc: 0.5079
Epoch 6/50, Train Loss: 0.4684, Train Acc: 0.8726, Val Loss: 0.4079, Val Acc: 0.9008
Epoch 11/50, Train Loss: 0.2408, Train Acc: 0.9284, Val Loss: 0.2429, Val Acc: 0.9444
Epoch 16/50, Train Loss: 0.1555, Train Acc: 0.9602, Val Loss: 0.2006, Val Acc: 0.9325
Epoch 21/50, Train Loss: 0.1237, Train Acc: 0.9632, Val Loss: 0.1611, Val Acc: 0.9524
Epoch 26/50, Train Loss: 0.0977, Train Acc: 0.9721, Val Loss: 0.1425, Val Acc: 0.9484
Epoch 31/50, Train Loss: 0.0837, Train Acc: 0.9692, Val Loss: 0.1255, Val Acc: 0.9603
Epoch 36/50, Train Loss: 0.0597, Train Acc: 0.9821, Val Loss: 0.1124, Val Acc: 0.9643
Epoch 41/50, Train Loss: 0.0480, Train Acc: 0.9881, Val Loss: 0.1341, Val Acc: 0.9563
Epoch 46/50, Train Loss: 0.0397, Train Acc: 0.9891, Val Loss: 0.1160, Val Acc: 0.9643
Epoch 50/50, Train Loss: 0.0339, Train Acc: 0.9920, Val Loss: 0.1333, Val Acc: 0.9484
Test accuracy: 0.967
Sample prediction classes:
Prediction: 6, Actual: 6
Prediction: 9, Actual: 9
Prediction: 3, Actual: 3
Prediction: 7, Actual: 7
Prediction: 2, Actual: 2
Prediction: 2, Actual: 1
Prediction: 5, Actual: 5
Prediction: 2, Actual: 2
Prediction: 5, Actual: 5
Prediction: 2, Actual: 2
Prediction: 1, Actual: 1
Prediction: 8, Actual: 9
Prediction: 4, Actual: 4
Prediction: 0, Actual: 0
Prediction: 4, Actual: 4
Training vs Validation Accuracy of PyTorch Model
Training and validation-accuracy curves over 50 epochs for the PyTorch example above.

Comparison: TensorFlow vs. PyTorch

TensorFlow has 187k stars on GitHub, and PyTorch has 85k.

Feature TensorFlow PyTorch
Computation Graph Static or dynamic Dynamic
Ease of Use Simplified with Keras Intuitive and Pythonic
Ecosystem Extensive (Hub, Lite, etc.) Growing rapidly
Deployment Optimized for production Strong focus on research

Conclusion

We’ll talk more about TensorFlow and PyTorch in the deep learning section.

I’m sure you’re wondering which one I like better…

oh… what’s that? You don’t really care?

Well, it’s PyTorch 😜.

Key Takeaways

  • Scikit-learn provides an intuitive API for traditional machine learning tasks and is great for beginners
  • TensorFlow offers a comprehensive ecosystem for deep learning and production deployment
  • PyTorch’s dynamic computation graphs make it popular for research and experimentation
  • Each library has its strengths - choose based on your specific needs and use case

Next: MLOps

Right then. Now that you know about PyTorch being my favorite (admit it, you did care!), let’s move right along to MLOps.

Comments (0)

No comments yet.