⚡ What is Deep Learning?
Deep Learning is a specialized subset of machine learning based on multi-layered Artificial Neural Networks (ANNs). By stacking successive hidden layers with non-linear activation functions (such as ReLU, GELU, and Sigmoid), deep architectures autonomously discover hierarchical feature representations directly from raw data without manual feature extraction. In Python, frameworks like PyTorch accelerate these computations across multi-core GPUs and CPUs via dynamic computational graphs, tensor arithmetic, and reverse-mode automatic differentiation (autograd).
requires_grad=True to automatically compute exact partial derivatives via the chain rule during backward().
import torch
# Input features (x), true target (y), and trainable weight (w)
x = torch.tensor([2.0, 4.0], dtype=torch.float32)
y_target = torch.tensor([8.0, 16.0], dtype=torch.float32)
w = torch.tensor([1.5, 1.5], dtype=torch.float32, requires_grad=True)
# 1. Forward Pass: Linear Prediction (y_pred = w * x)
y_pred = w * x
# 2. Mean Squared Error (MSE) Loss
loss = ((y_pred - y_target) ** 2).mean()
# 3. Backward Pass: Compute d(Loss)/dw automatically
loss.backward()
print(f"Predictions: {y_pred.detach().numpy()}")
print(f"Computed MSE Loss: {loss.item():.4f}")
print(f"Gradients on Weights (dL/dw): {w.grad.numpy()}")
nn.Module to classify multi-variable transaction patterns into legitimate vs. fraudulent activity.
import torch
import torch.nn as nn
class FraudDetectionMLP(nn.Module):
"""Deep Multi-Layer Perceptron with Batch Normalization and Dropout."""
def __init__(self, input_dim: int = 4):
super(FraudDetectionMLP, self).__init__()
self.network = nn.Sequential(
nn.Linear(input_dim, 16),
nn.BatchNorm1d(16),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(16, 8),
nn.ReLU(),
nn.Linear(8, 1),
nn.Sigmoid()
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.network(x)
model = FraudDetectionMLP(input_dim=4)
model.eval()
# Transaction: [amount_normalized, hour_normalized, foreign_tx_flag, device_trust_score]
sample_tx = torch.tensor([[0.95, 0.12, 1.0, 0.15]], dtype=torch.float32)
with torch.no_grad():
fraud_prob = model(sample_tx).item()
print(f"Input Features: {sample_tx.numpy()}")
print(f"Deep Neural Fraud Probability: {fraud_prob * 100:.2f}%")
print("Action:", "TRIGGER MFA CHALLENGE" if fraud_prob > 0.50 else "APPROVE")
import torch
import torch.nn as nn
import torch.optim as optim
# Synthetic training batch: 4 samples with 2 input features
X_train = torch.tensor([[1.0, 2.0], [2.0, 3.0], [8.0, 9.0], [9.0, 8.0]], dtype=torch.float32)
y_train = torch.tensor([[0.0], [0.0], [1.0], [1.0]], dtype=torch.float32)
simple_net = nn.Sequential(
nn.Linear(2, 4),
nn.ReLU(),
nn.Linear(4, 1),
nn.Sigmoid()
)
criterion = nn.BCELoss()
optimizer = optim.Adam(simple_net.parameters(), lr=0.05)
# Train across 5 epochs
for epoch in range(1, 6):
optimizer.zero_grad() # 1. Clear cached gradients
predictions = simple_net(X_train) # 2. Forward pass
loss = criterion(predictions, y_train) # 3. Compute Binary Cross-Entropy
loss.backward() # 4. Backpropagation
optimizer.step() # 5. Update weights via Adam
print(f"Epoch {epoch}/5 -> Loss: {loss.item():.4f}")
import torch
import torch.nn as nn
class VisualInspectionCNN(nn.Module):
"""Convolutional network classifying visual rendering anomalies from UI screenshot patches."""
def __init__(self):
super(VisualInspectionCNN, self).__init__()
# Conv2d: 1 input channel (grayscale), 8 feature maps, 3x3 kernel
self.conv = nn.Conv2d(in_channels=1, out_channels=8, kernel_size=3, padding=1)
self.relu = nn.ReLU()
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
# 16x16 pooled down to 8x8 with 8 feature maps = 8 * 8 * 8 = 512
self.classifier = nn.Linear(8 * 8 * 8, 2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.pool(self.relu(self.conv(x)))
x = x.view(x.size(0), -1) # Flatten feature maps
return self.classifier(x)
cnn = VisualInspectionCNN()
cnn.eval()
# Batch: 1 screenshot patch, 1 channel (grayscale), 16x16 resolution
mock_ui_patch = torch.randn(1, 1, 16, 16)
output_logits = cnn(mock_ui_patch)
predicted_class = torch.argmax(output_logits, dim=1).item()
labels = {0: "Clean Render (Pixel Match)", 1: "Visual Defect (Alignment Shift)"}
print(f"Output Raw Logits: {output_logits.detach().numpy()}")
print(f"Visual Classification: {labels[predicted_class]}")
import torch
import torch.nn as nn
class TelemetryForecastingLSTM(nn.Module):
"""LSTM modeling sequential timeseries metrics across past timesteps."""
def __init__(self, input_dim: int = 1, hidden_dim: int = 16):
super(TelemetryForecastingLSTM, self).__init__()
self.lstm = nn.LSTM(input_size=input_dim, hidden_size=hidden_dim, batch_first=True)
self.regressor = nn.Linear(hidden_dim, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
lstm_out, _ = self.lstm(x)
# Take hidden state representation from the final timestep
last_timestep = lstm_out[:, -1, :]
return self.regressor(last_timestep)
lstm_model = TelemetryForecastingLSTM()
lstm_model.eval()
# Sequence: 1 batch, 5 past consecutive timesteps of CPU load (e.g., [42%, 45%, 52%, 60%, 75%])
telemetry_sequence = torch.tensor([[[42.0], [45.0], [52.0], [60.0], [75.0]]], dtype=torch.float32)
with torch.no_grad():
forecasted_cpu = lstm_model(telemetry_sequence).item()
print(f"Historical 5-Timestep Window: {[step[0] for step in telemetry_sequence[0].numpy()]}")
print(f"Forecasted CPU for Next Timestep (t+1): {forecasted_cpu:.2f}%")
import torch
import torch.nn.functional as F
import math
# Sequence of 3 token embedding vectors of dimension d_k = 4
# Tokens: ["User", "clicked", "button"]
query = torch.tensor([[1.0, 0.0, 1.0, 0.0],
[0.0, 2.0, 0.0, 1.0],
[1.0, 1.0, 0.0, 0.0]], dtype=torch.float32)
key = query.clone()
value = query.clone()
d_k = query.size(-1)
# 1. Matmul Q and K^T, scaled by sqrt(d_k)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
# 2. Softmax produces normalized attention weights
attention_weights = F.softmax(scores, dim=-1)
# 3. Contextual output representations (Weights * Value)
contextual_output = torch.matmul(attention_weights, value)
print("Computed Attention Matrix (3x3 Token Relationships):")
print(np_matrix := np_round := torch.round(attention_weights, decimals=3).numpy())
print("\nContextualized Token Representation for 'button' (Token 3):")
print(torch.round(contextual_output[2], decimals=3).numpy())
import torch
import torch.nn as nn
class TelemetryAutoencoder(nn.Module):
"""Compresses 4 features down to 2 latent variables and reconstructs output."""
def __init__(self):
super(TelemetryAutoencoder, self).__init__()
self.encoder = nn.Sequential(
nn.Linear(4, 2),
nn.ReLU()
)
self.decoder = nn.Sequential(
nn.Linear(2, 4),
nn.ReLU()
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
latent = self.encoder(x)
return self.decoder(latent)
autoencoder = TelemetryAutoencoder()
autoencoder.eval()
# Clean baseline telemetry vs Severe anomaly spike
normal_telemetry = torch.tensor([[10.0, 15.0, 12.0, 14.0]], dtype=torch.float32)
corrupted_telemetry = torch.tensor([[950.0, 890.0, 12.0, 14.0]], dtype=torch.float32)
criterion = nn.MSELoss()
with torch.no_grad():
loss_normal = criterion(autoencoder(normal_telemetry), normal_telemetry).item()
loss_corrupt = criterion(autoencoder(corrupted_telemetry), corrupted_telemetry).item()
print(f"Normal Telemetry Reconstruction Loss: {loss_normal:.2f} (Low error -> Expected)")
print(f"Corrupted Anomaly Reconstruction Loss: {loss_corrupt:.2f} (High error -> Alert)")
import torch
import torch.nn as nn
# 1. Simulate a large pre-trained backbone network
class PretrainedBackbone(nn.Module):
def __init__(self):
super().__init__()
self.features = nn.Sequential(
nn.Linear(10, 32),
nn.ReLU(),
nn.Linear(32, 64)
)
def forward(self, x): return self.features(x)
backbone = PretrainedBackbone()
# 2. Freeze backbone parameters to preserve pre-trained knowledge
for param in backbone.parameters():
param.requires_grad = False
# 3. Attach custom trainable classification head
class CustomFineTunedClassifier(nn.Module):
def __init__(self, base_model):
super().__init__()
self.base = base_model
self.custom_head = nn.Linear(64, 2) # Binary task
def forward(self, x):
features = self.base(x)
return self.custom_head(features)
transfer_model = CustomFineTunedClassifier(backbone)
trainable_params = sum(p.numel() for p in transfer_model.parameters() if p.requires_grad)
frozen_params = sum(p.numel() for p in transfer_model.parameters() if not p.requires_grad)
print(f"Frozen Backbone Weights: {frozen_params} parameters")
print(f"Trainable Custom Head: {trainable_params} parameters (Fast fine-tuning)")
torch.save) when performance hits an all-time minimum.
import torch
import torch.nn as nn
import tempfile
import os
class EarlyStoppingController:
"""Monitors validation loss and preserves best model weights checkpoint."""
def __init__(self, patience: int = 2):
self.patience = patience
self.best_loss = float('inf')
self.counter = 0
self.checkpoint_path = os.path.join(tempfile.gettempdir(), "best_deep_model.pt")
def evaluate_step(self, val_loss: float, model: nn.Module) -> bool:
if val_loss < self.best_loss:
self.best_loss = val_loss
self.counter = 0
torch.save(model.state_dict(), self.checkpoint_path)
print(f" ✓ Checkpoint Saved! (New best loss: {val_loss:.4f})")
return False
else:
self.counter += 1
print(f" ⚠ Validation loss worsened ({val_loss:.4f}). Counter: {self.counter}/{self.patience}")
if self.counter >= self.patience:
print(" ⛔ Early stopping triggered to halt overfitting.")
return True
return False
monitor = EarlyStoppingController(patience=2)
dummy_model = nn.Linear(2, 1)
simulated_val_losses = [0.85, 0.62, 0.51, 0.54, 0.58]
for epoch, loss in enumerate(simulated_val_losses, 1):
print(f"Epoch {epoch}: Val Loss = {loss:.4f}")
should_stop = monitor.evaluate_step(loss, dummy_model)
if should_stop:
break
import torch
import torch.nn as nn
import tempfile
import os
class InferenceServiceNet(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(3, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x): return self.sigmoid(self.fc(x))
deploy_model = InferenceServiceNet()
deploy_model.eval()
# Dummy input matching the expected input tensor shape [batch_size, 3]
dummy_input = torch.randn(1, 3, requires_grad=False)
onnx_filepath = os.path.join(tempfile.gettempdir(), "production_inference.onnx")
# Export PyTorch model graph into static ONNX binary representation
torch.onnx.export(
deploy_model,
dummy_input,
onnx_filepath,
input_names=["telemetry_input"],
output_names=["risk_score"],
opset_version=14
)
print(f"Exported Model File Size: {os.path.getsize(onnx_filepath)} bytes")
print(f"Saved ONNX Model to: {onnx_filepath}")
print("Status: Ready for cross-platform deployment on C++, Go, Java, or Python.")