Class-Weighted Soft-Margin Linear SVM
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `compute_sample_costs`, `fit_weighted_svm`, `decision_function` and `predict` for a linear SVM with per-sample penalties `C_i = C · weight[y_i]`. Training minimizes `0.5·(‖w‖² + b²) + Σ C_i·max(0, 1 − y_i(w·x_i + b))` (the bias is regularized, as with an appended constant feature of 1).
```python
def compute_sample_costs(y, C=1.0, class_weight=None): ...
def fit_weighted_svm(X, y, C=1.0, class_weight=None, max_epochs=1000, tol=1e-8): ...
def decision_function(X, w, b): ...
def predict(X, w, b): ...
```
Requirements:
- `class_weight=None` gives every sample weight 1. A dict maps label to weight, with `1.0` for a label missing from it. `"balanced"` gives `n / (n_classes · count[label])`.
- Raise `ValueError` for labels outside `{-1, +1}`, an unknown string, or any other `class_weight` type.
- `fit_weighted_svm` returns `(w, b, alpha)`: `w` of shape `(d,)`, `b` a float, and the dual `alpha` of shape `(n,)` with `0 ≤ alpha_i ≤ C_i`, `w = Σ alpha_i y_i x_i` and `b = Σ alpha_i y_i`.
- Iterate at most `max_epochs` passes, stopping once the largest KKT (projected-gradient) violation is below `tol`.
- `decision_function` returns `X @ w + b`. `predict` returns int `+1` when the value is `>= 0`, else `-1`.
- Use NumPy only. Results are checked against scikit-learn's `LinearSVC(loss="hinge", class_weight=...)` and against the KKT conditions.
Example:
```python
compute_sample_costs([1, 1, 1, -1], C=2.0, class_weight="balanced")
# -> array([1.3333, 1.3333, 1.3333, 4.0]) (rounded)
fit_weighted_svm([[1.0], [-1.0]], [1, -1], C=0.4, class_weight={1: 1.0, -1: 0.5})
# -> w=array([0.6]), b=0.2, alpha=array([0.4, 0.2])
```
In the first call there are four samples, three labeled +1 and one labeled -1, so the balanced weights are 4/6 and 4/2. Multiplying by `C = 2` gives 4/3 for each positive sample and 4 for the negative one.
```hint Where the weights go
Write down the dual of the weighted problem next to the unweighted one. Only one part of it changes.
```
```hint Stopping at a bound
When a dual variable sits at 0 or at its upper bound, part of its gradient points out of the feasible box. Decide which part should count toward the violation you compare with `tol`.
```
### Constraints & Assumptions
- `X` has shape `(n, d)` and every label is -1 or +1.
- Defaults are `C=1.0`, `max_epochs=1000` and `tol=1e-8`.
- NumPy only, with no solver libraries.
### Clarifying Questions to Ask
- Can a class weight be zero or negative, and what should happen if it is?
- When one class is absent from `y`, should `"balanced"` count only the classes that are present?
- Is a fixed sample order in every epoch acceptable, or should the order be shuffled the way liblinear does it?
### What a Strong Answer Covers
- How the class weights and the regularized bias change the dual problem.
- A coordinate descent update with the exact one-dimensional step, clipping to `[0, C_i]`, and an incremental update of `w` and `b`.
- The projected-gradient stopping rule at the lower bound, at the upper bound and inside the box.
- Correct costs for all three `class_weight` forms, with the required `ValueError` cases.
- How to verify the result against `LinearSVC` and the KKT conditions, and which outputs can legitimately differ.
### Follow-up Questions
- Why is `(w, b)` unique while `alpha` may not be, and when does that happen?
- How does class weighting compare with oversampling the minority class?
- What changes in the dual and in the solver if the bias is not regularized?
Overview: Implement a soft-margin linear SVM with per-class penalties, trained by dual coordinate descent with a regularized bias. Tests deriving the weighted dual, projected-gradient stopping rules, balanced class weights, and checking a NumPy solver against the KKT conditions and LinearSVC.