To calculate the R2 score in Python using sklearn library, you can follow these steps:
Import the necessary libraries:
main.py37 chars2 lines
Prepare your predicted values and actual target values. Let's assume you have predicted values stored in a list y_pred
and actual target values stored in a list y_true
.
Calculate the R2 score using the r2_score
function:
main.py42 chars2 lines
The r2_score
function calculates the R2 score for regression models. It takes two arguments: y_true
, which represents the true target values, and y_pred
, which represents the predicted target values. The function returns the R2 score as a floating-point number between -inf and 1.
Here's an example that demonstrates how to calculate the R2 score:
main.py167 chars8 lines
Output:
main.py29 chars2 lines
The higher the R2 score, the better the model fits the data.
Make sure you have the sklearn library installed before running the code:
main.py25 chars2 lines
Note that the R2 score can be negative if the model's predictions are worse than the mean of the target values.
I hope this helps! Let me know if you have any further questions.
gistlibby LogSnag