Knowledge / Artificial Intelligence and Data Science / Python ML libraries: scikit-learn, PyTorch and TensorFlow

Python ML libraries: scikit-learn, PyTorch and TensorFlow

Artificial Intelligence and Data Science (B.E./B.Tech) · Programming and data · free study notes for exams, placements and interviews

In short

scikit-learn, PyTorch and TensorFlow (with Keras) are the three libraries that carry almost all production machine learning in Python. scikit-learn is the classical-ML workhorse for tabular data — one uniform fit/predict API over regression, classification, clustering and model selection; PyTorch and TensorFlow are deep-learning frameworks built on GPU tensors and automatic differentiation, used for vision, speech, text and recommendation models. Final-year AI&DS labs, AICTE model-curriculum practicals and NPTEL courses are built around them, and the GATE DA (Data Science and AI) paper examines the mathematics they implement — loss functions, gradient descent, regularisation and evaluation metrics — even though it does not ask about API syntax. In Indian hiring (TCS, Infosys, Wipro, Accenture, Fractal, Mu Sigma, ZS, Flipkart, Swiggy, Razorpay, Jio, HDFC, Krutrim, Sarvam AI) a data-science interview almost always includes "walk me through your scikit-learn pipeline" and "write a PyTorch training loop". All three are free and open source (scikit-learn BSD-3, PyTorch BSD-style, TensorFlow Apache 2.0).

Explained

Which library for which job

The scikit-learn estimator API

PyTorch: tensors, autograd and the training loop

model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 3))
crit, opt = nn.CrossEntropyLoss(), torch.optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(10):
    model.train()
    for xb, yb in train_loader:
        xb, yb = xb.to(device), yb.to(device)
        opt.zero_grad()
        loss = crit(model(xb), yb)   # yb = int64 class indices
        loss.backward()
        opt.step()

TensorFlow and Keras

Training mechanics common to both frameworks

Key points

Formulas and examples

Mean squared error: MSE = (1/n) Σ(yᵢ − ŷᵢ)² — y actual, ŷ predicted, n samples; RMSE = √MSE (same unit as y, e.g. ₹)
Coefficient of determination: R² = 1 − SS_res/SS_tot = 1 − Σ(yᵢ−ŷᵢ)² / Σ(yᵢ−ȳ)² (dimensionless)
Binary cross-entropy: L = −(1/n) Σ [yᵢ ln pᵢ + (1−yᵢ) ln(1−pᵢ)] — p = predicted probability
Categorical cross-entropy: L = −(1/n) Σᵢ Σ_c y_{ic} ln p_{ic} (nats, natural log)
Sigmoid σ(z) = 1/(1+e−z); Softmax p_c = e^{z_c} / Σ_j e^{z_j}
Gradient descent: θ ← θ − η ∂L/∂θ — η learning rate (dimensionless step scale)
SGD with momentum: v ← βv + ∂L/∂θ; θ ← θ − η v (β ≈ 0.9)
Adam: m ← β₁m + (1−β₁)g; v ← β₂v + (1−β₂)g²; m̂ = m/(1−β₁ᵗ); v̂ = v/(1−β₂ᵗ); θ ← θ − η·m̂/(√v̂ + ε) (β₁=0.9, β₂=0.999, ε≈10⁻⁸; 10⁻⁷ in Keras)
L2 (weight decay): L_total = L + λ Σθ²; scikit-learn uses C = 1/(2λ)-like inverse strength — larger C means weaker regularisation
Standardisation (StandardScaler): z = (x − μ)/σ, fitted on training data only
Steps per epoch = ⌈N/B⌉ — N training samples, B batch size; total updates = epochs × steps
Dense layer parameters = (n_in + 1) × n_out; Conv2D parameters = (k_h × k_w × C_in + 1) × C_out
Conv/pool output size = ⌊(W − K + 2P)/S⌋ + 1 — W input size, K kernel, P padding, S stride ("same" padding with S=1 keeps W)
Accuracy = (TP+TN)/(TP+TN+FP+FN); Precision = TP/(TP+FP); Recall = TP/(TP+FN); F1 = 2PR/(P+R) = 2TP/(2TP+FP+FN)
Fits in a grid search = (Π of parameter-value counts) × k + 1 refit

Example 1 — classification report from a confusion matrix. A fraud classifier on 1,000 test transactions gives TP = 120, FP = 30, FN = 20, TN = 830.

Example 2 — one gradient-descent step, hand versus autograd. Model ŷ = w·x, loss L = (ŷ − y)², with x = 2, y = 5, initial w = 1, η = 0.1.

Example 3 — softmax and cross-entropy from logits. A 3-class head outputs logits z = [2.0, 1.0, 0.1]; true class is 0.

Example 4 — parameter counts (MNIST-style). Keras MLP: Input 784 → Dense 128 (ReLU) → Dense 64 (ReLU) → Dense 10 (softmax).

Example 5 — training budget and search cost. N = 60,000 training images, batch size B = 128, 10 epochs.

Aspectscikit-learnPyTorchTensorFlow / Keras
Main useClassical ML on tabular dataDeep learning, researchDeep learning, production
Core APIfit / predict / transformTensors, nn.Module, autogradKeras compile / fit; GradientTape
GraphNoneDynamic (define-by-run)Eager, graph via @tf.function
GPU / TPUNoCUDA/ROCm GPUsGPUs and TPUs
Training loopHidden inside fitWritten by youfit, or custom with a tape
Save formatjoblib picklestate_dict, TorchScript, ONNX.keras, SavedModel, TFLite
DeploymentFlask/FastAPI serviceTorchServe, ONNX RuntimeTF Serving, TFLite, TFX, TF.js
Learning curveEasiestPythonic, moderateEasy with Keras, deep stack below

Where it is used

Interview questions

Common mistakes

Related topics

Machine learning algorithms and model evaluation · Deep learning and neural networks · Python for data analysis: NumPy and pandas · Data cleaning and feature engineering · Model deployment and MLOps · Natural language processing and computer vision.

Open in the Knowledge reader →Find jobs →