Sweep C for a Linear Soft-Margin SVC
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `sweep_linear_svc(X, y, C_values)`. For each `C`, fit `SVC(kernel="linear", C=C)` on the 2D dataset and summarise the fit. Return a list of dicts in the same order as `C_values`.
The output must meet these requirements:
- Each dict has exactly the keys `"C"`, `"n_support"`, `"margin_width"`, `"train_accuracy"`.
- `"C"` is a `float`. `"n_support"` is an `int` equal to `len(model.support_)`.
- `"margin_width"` is `2 / ||w||` (L2 norm of `model.coef_`).
- `"train_accuracy"` is the fraction of training points predicted correctly, as a `float`.
- Results must match scikit-learn's `SVC` with default settings otherwise.
Example:
```python
X = [[-1, 0], [-2, 1], [1, 0], [2, -1]]
y = [-1, -1, 1, 1]
sweep_linear_svc(X, y, [1000.0])
# [{'C': 1000.0, 'n_support': 2, 'margin_width': ~2.0, 'train_accuracy': 1.0}]
```
The margin width is about 2.0, up to the solver's tolerance.
```hint Where the numbers live
A fitted linear `SVC` already exposes its weight vector, the indices of its support vectors and its predictions. Every value you need comes from one of those. Check the types too: numpy scalars are not plain Python floats and ints.
```
### Constraints & Assumptions
- `X` has shape (n, 2) and `y` holds two class labels, so `model.coef_` has a single row.
- Every value in `C_values` is positive. scikit-learn rejects `C <= 0`.
- No feature scaling, class weights or other changes to `SVC`: the numbers must match a default fit on the raw `X`.
### What a Strong Answer Covers
- Fitting a fresh linear `SVC` for each `C` and returning the summaries in input order.
- Reading the weight vector from the fitted model and explaining why `2 / ||w||` is the margin width.
- Producing plain Python `float` and `int` values for every key.
- How `C` trades margin width against training errors, and what that does to the support vector count.
- Edge cases: a zero weight vector, a single class, labels that are not -1 and 1.
### Follow-up Questions
- Why does a smaller `C` widen the margin and recruit more support vectors?
- This function breaks for `kernel="rbf"`. Why, and how would you compute the margin width there?
- Training accuracy usually rises with `C`. How would you choose `C` for a model that has to generalize?
- How does rescaling one feature change the margin width you report?
Overview: Implement a function that fits a linear soft-margin SVC in scikit-learn for each value of C and reports the support vector count, margin width and training accuracy. It tests how the C penalty trades margin width against training errors and how to read a fitted SVM's attributes.