You are on page 1of 1

7/21/23, 4:52 PM R Squared Function Python

R Squared Function Python


def r_squared(actual, predicted):
"""
Compute the R-squared statistic.

Parameters:
actual (list or numpy array): The actual (observed) values of the de
predicted (list or numpy array): The predicted values of the depende

Returns:
float: The R-squared statistic rounded to 5 decimal points.
"""
if len(actual) != len(predicted):
raise ValueError("Length of actual and predicted lists should be the

mean_actual = sum(actual) / len(actual)


ss_total = sum((actual_i - mean_actual) ** 2 for actual_i in actual)
ss_residual = sum((actual_i - predicted_i) ** 2 for actual_i, predicted_

r_squared = 1.0 - (ss_residual / ss_total)


return round(r_squared, 5)

# Test case
y_actual = [0.00, 56.92, 100.00]
y_predicted = [0.00, 100.0, 97.46]

r_squared_value = r_squared(y_actual, y_predicted)


print("R-squared:", r_squared_value)

Now, when you run the code, the R-squared value will be rounded to 5 decimal points, giving
you the output: `R-squared: 0.62989`.

Send a message

Free Research Preview. ChatGPT may produce inaccurate information about people, places, or facts. ChatGPT July 20 Version

https://chat.openai.com/c/4856747c-1738-4930-ba5a-ed007096f961 1/1

You might also like