Machine learning: optimization, data and core algorithms

Machine learning: optimization, data and core algorithms

Учебные материалы

Training: prediction → error → weight update

Parameters (weights) determine a model's prediction. A loss measures error. The gradient describes how loss changes with each parameter; gradient descent updates weights against its direction of increase.

Machine learning: optimization, data and core algorithms: mechanism diagram with an example

L(w) = (w − 3)² · η = 0.2

94034Lw
Шаг 0/6w = 0L = 9∂L/∂w = -6

wnext = 0 − 0.2 × (-6) = 1.2

Градиент здесь отрицательный: вычитая его, увеличиваем w. При скорости обучения η = 0.2 точка приближается к минимуму, а ошибка уменьшается. Слишком большая скорость обучения может привести к росту ошибки.

One gradient-descent step

  1. Compute the loss: L(w) = (w − 4)².
  2. Differentiate: dL/dw = 2(w − 4). At w = 1, the gradient is −6.
  3. Update: w_new = w − η × gradient. With η = 0.1, the result is 1 − 0.1 × (−6) = 1.6.
  4. Error decreases: L(1) = 9, L(1.6) = 5.76.

The learning rate η controls step size. An excessive step can overshoot a minimum, causing oscillation or increasing error.

Losses and gradients

  • MSE (Mean Squared Error) averages squared errors. Errors of 1 and 3 give (1² + 3²) / 2 = 5. Large errors receive especially large penalties.
  • Cross-entropy for one true class is −ln(p_true). Higher probability for the correct class means lower loss.
  • Softmax converts logits (numerical class scores) into probabilities: p_i = exp(z_i) / Σexp(z_j). Adding the same constant to all logits introduces a common factor that cancels: [0, 0] and [5, 5] both give [0.5, 0.5].
  • Backpropagation computes derivatives using the chain rule. If u = 2w, L = u² and w = 3, then dL/dw = (2u) × 2 = 12 × 2 = 24.

Batches, accumulation and clipping

TechniqueWhat changes
Full batchEach update uses the entire training set.
Mini-batchEach update uses a subset; updates cost less and gradients are noisier.
Gradient accumulationSeveral micro-batches contribute to one optimizer step. Three batches of 4 examples, correctly averaged, give an effective batch of 12.
Norm clippingBounds gradient length while preserving direction. [6, 8] has norm 10; a cap of 5 gives [3, 4].

For nonzero g, clipping computes g × min(1, C / ||g||). A zero gradient stays unchanged.

Data splits without leakage

SplitPurpose
TrainFit model weights and StandardScaler means/variances.
ValidationSelect settings and the early-stopping point.
TestFinal evaluation after selecting settings.
  • Future prediction: train on earlier data and evaluate on a later period.
  • New-customer prediction: split by customer instead of randomly mixing similar records from each customer.
  • Fit the scaler on train only; apply the fitted transformation to validation/test.
  • Falling training loss with rising validation loss can indicate overfitting. Early stopping selects a checkpoint using validation; do not select the epoch using the final test.

Regularization and classification

  • L2 adds a λw² penalty and gradient 2λw. With λ = 0.1 and w = 3, the extra gradient is 0.6.
  • Dropout randomly disables elements during training; disable it for standard deterministic inference.
  • Class weights change examples' contributions to loss, not their actual count.
  • A threshold predicts positive when p ≥ threshold. Lowering it cannot decrease predicted-positive count; precision need not increase.

Trees and ensembles

MethodMechanism
Decision treePartitions data using feature conditions. A depth limit restricts complexity.
Random forestCombines trees built with randomized data and feature choices, reducing dependence among their errors.
Gradient boostingAdds trees sequentially to correct current errors. For squared-error loss, residual = y − prediction: 8 − 6 = 2.

Gini impurity = 1 − Σp_i²: two equal class shares give 0.5; a pure node gives 0. A lower boosting learning rate reduces each tree's contribution; keeping the same tree count can underfit.

Clustering and dimensionality reduction

  • K-means: assign a point to the nearest centroid, then update centroids using the mean. Points [1, 3, 8] give a centroid of 4. Feature scales affect distances and assignments.
  • DBSCAN (Density-Based Spatial Clustering of Applications with Noise): forms density-based clusters. Noise means a point was not assigned to a cluster at the chosen settings, not that its measurement is necessarily wrong.
  • PCA (principal component analysis): its first component maximizes projected variance of centered data and is generally a combination of features. Centering subtracts the mean; standardization also changes scale. Scikit-learn PCA does not automatically equalize feature variances.

Retained variance: for shares [0.60, 0.25, 0.15], two components retain 0.60 + 0.25 = 85%; reaching 90% requires all three.