Fit multiple linear regression with an intercept and predict new rows
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `predict_new(X_train, y_train, X_new)` that fits an ordinary least squares (OLS) regression with an intercept of `y_train` on `X_train`, then predicts `y` for the rows of `X_new`. Any OLS technique (closed form, `numpy`, or `sklearn`) is accepted.
Requirements:
- Fit on `X_train` of shape `(n, p)` and `y_train` of shape `(n,)` only. Do not re-fit on `X_new`.
- `X_new` has shape `(m, p)` with the same columns in the same order.
- Return a 1-D `np.ndarray` of shape `(m,)`, one prediction per row of `X_new` in row order.
Example (the training data follows `y = 1 + 2*x1 - x2` exactly):
```python
X_train = np.array([[0., 0.], [1., 0.], [0., 1.], [1., 1.], [2., 1.]])
y_train = np.array([1., 3., 0., 2., 4.])
X_new = np.array([[3., 2.], [-1., 0.]])
predict_new(X_train, y_train, X_new) # array([ 5., -1.])
```
```hint Learn from the training rows only
Everything the model estimates (the slopes and the intercept) must come from `X_train` and `y_train`. `X_new` is only combined with what was learned. If you solve it with NumPy, think about where the intercept lives in the design matrix.
```
### Constraints & Assumptions
- Inputs are float `np.ndarray`s built by the grader, for example `n = 40`, `p = 3`, `m = 5`.
- There are no NaNs and no reshaping is needed.
### What a Strong Answer Covers
- Fitting the coefficients and the intercept on the training arrays only, then applying them to `X_new`.
- Handling the intercept correctly in a manual solution, with the same augmentation applied to both matrices.
- Returning a 1-D float array of length `m` in row order.
- Choosing a numerically stable solver and knowing what happens when columns are collinear.
- The cost of fitting and of predicting.
### Follow-up Questions
- How would you add the bias (intercept) by hand with `numpy` instead of relying on `sklearn`?
- Why should you never call `fit` on `X_new`?
- What happens to the coefficients and to the predictions when two columns of `X_train` are perfectly collinear?
- If you standardize the features before fitting, which statistics do you use to transform `X_new`?
Overview: Write a Python function that fits ordinary least squares with an intercept on a training feature matrix and returns one prediction per row of a new matrix. It tests keeping fitting separate from prediction, handling the intercept in NumPy or scikit-learn, and returning the right output shape.