All changes saved to local database
ML - discrete structures
Instructions

Loss Function measures how wrong a model's predictions are. Think of it as a score that tracks the distance between reality and expectation. The most common tool for this is the Mean Squared Error (MSE). It quantifies the average squared distance between the predicted values and the actual target values. In any regression task, like predicting house prices or stock trends, a lower MSE indicates a more accurate model.

Methodology

To calculate the MSE for a set of predictions, we follow a three-step mathematical pipeline:

Step 1: Calculate the Error (Residuals) Subtract the Predicted Vector (y^\hat {y}) from the Actual Vector (yy) to find the raw difference for every data point.

Error=yy^\text{Error} = y - \hat{y}

Step 2: Square the Errors Square each individual error. This ensures all values are positive and penalizes larger errors more heavily than smaller ones.

Squared Error=(Error)2\text{Squared Error} = (\text{Error})^2

Step 3: Calculate the Mean Find the average of all the squared errors by summing them up and dividing by the total number of observations (nn).

MSE=1ni=1n(yiy^i)2MSE = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2

Implementation

Although standard loops can be used to calculate the Mean Squared Error (MSE), they become inefficient when working with large datasets. Instead, we leverage NumPy's vectorization capabilities, which allow operations to be performed on entire arrays simultaneously. By subtracting one array from another, squaring the resulting differences, and then applying np.mean(), the entire calculation can be completed efficiently without the need for explicit loops.

System Note: Your coding environment is already pre-configured to run NumPy. You can access it directly by using the import numpy as np statement.

Validation

To ensure your solution passes our automated verification system (==), you must perform the following formatting steps before returning your result:

  1. Compute Mean: Use the np.mean() function for the final calculation.
  2. Precision: Round the final scalar result to 4 decimal places using the Python round(value, 4) function.
  3. Data Type: The returned value must be a standard Python float.

The Challenge

Implement the function calculate_mse(actual, predicted). It must accept two 1D NumPy arrays and return the Mean Squared Error as a rounded float.

import numpy as np def calculate_mse(actual, predicted): # Step 1 & 2: Calculate the squared difference between actual and predicted # Step 3: Find the mean of those squares using np.mean() # Final Step: Round the result to 4 decimal places and return pass
solution.py
Terminal