Calculate Root Mean Square Error (RMSE)
Task: Compute Root Mean Square Error (RMSE)
In this task, you are required to implement a function rmse(y_true, y_pred)
that calculates the Root Mean Square Error (RMSE) between the actual values and the predicted values. RMSE is a commonly used metric for evaluating the accuracy of regression models, providing insight into the standard deviation of residuals.
Your Task:
Implement the function rmse(y_true, y_pred)
to:
- Calculate the RMSE between the arrays
y_true
andy_pred
. - Return the RMSE value rounded to three decimal places.
- Ensure the function handles edge cases such as:
- Mismatched array shapes.
- Empty arrays.
- Invalid input types.
The RMSE is defined as:
RMSE=1n∑i=1n(ytrue,i−ypred,i)2RMSE=n1i=1∑n(ytrue,i−ypred,i)2
Where:
- nn is the number of observations.
- ytrue,iytrue,i and ypred,iypred,i are the actual and predicted values for the ii-th observation.
Example:
Input:
y_true = np.array([3, -0.5, 2, 7]) y_pred = np.array([2.5, 0.0, 2, 8]) print(rmse(y_true, y_pred))
Output:
0.612
Reasoning:
The RMSE is calculated as sqrt((0.5^2 + 0.5^2 + 0^2 + 1^2) / 4) = 0.612
import numpy as np
def rmse(y_true, y_pred):
# Write your code here
MSE = np.mean((y_true - y_pred) ** 2)
rmse_res = np.sqrt(MSE)
return round(rmse_res,3)
Test Case Results
3 of 3 tests passed
官方题解
import numpy as np
def rmse(y_true, y_pred):
if y_true.shape != y_pred.shape:
raise ValueError("Arrays must have the same shape")
if y_true.size == 0:
raise ValueError("Arrays cannot be empty")
return round(np.sqrt(np.mean((y_true - y_pred) ** 2)), 3)