Click4Ai

57.

Easy

Implement the **Mean Squared Error (MSE)** loss function.

Formula:

MSE = (1/n) * sum((y_true - y_pred)^2)

Write a function mse(y_true, y_pred) that takes two arrays and returns the MSE value.

Example:

y_true = [3, 5, 2, 7]

y_pred = [2.5, 5.5, 2, 8]

Errors: [0.5, -0.5, 0, -1]

Squared: [0.25, 0.25, 0, 1]

MSE = (0.25 + 0.25 + 0 + 1) / 4 = 0.375

**Explanation:** MSE measures the average of the squared differences between predictions and actual values. It penalizes larger errors more heavily due to the squaring.

Constraints:

  • y_true and y_pred are 1D numpy arrays of equal length
  • Return a single float value
  • Do not use sklearn; implement from scratch
  • Test Cases

    Test Case 1
    Input: y_true=[3,5,2,7], y_pred=[2.5,5.5,2,8]
    Expected: 0.375
    Test Case 2
    Input: y_true=[1,2,3], y_pred=[1,2,3]
    Expected: 0.0
    Test Case 3
    Input: y_true=[0,0,0], y_pred=[1,1,1]
    Expected: 1.0
    + 2 hidden test cases