Solving tips
- RMSE is the square root of the mean of squared errors — build it inside-out: differences, square, mean, square root.
- Vectorize with NumPy: y_pred - y_true is an elementwise array, no Python loop needed.
- Guard the empty-input case so you don't divide by zero.
Implement root-mean-squared error (RMSE) from scratch with NumPy, without using a library metric function. RMSE is one of the most common regression metrics, and interviewers ask for it to check that you can turn a formula into vectorized code.
Definition
For n paired values, RMSE is the square root of the average squared difference between prediction and truth:
RMSE = sqrt( (1/n) * sum_i (y_pred[i] - y_true[i])^2 )
Task
Complete rmse(y_true, y_pred) so it returns the RMSE as a float. Both inputs are 1-D NumPy arrays of the same length. Do not call sklearn or any built-in RMSE/MSE helper.
Example
y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_pred = np.array([2.5, 5.0, 4.0, 8.0])
rmse(y_true, y_pred) # -> 0.9354143466934853
The squared errors are [0.25, 0.0, 2.25, 1.0], their mean is 0.875, and sqrt(0.875) ≈ 0.9354.
Constraints
1 <= n <= 10^6; use vectorized NumPy, not a Python loop.- Values fit in float64.