r2 score in python sklearn in python

To calculate the R2 score in Python using sklearn library, you can follow these steps:

  1. Import the necessary libraries:

    main.py
    from sklearn.metrics import r2_score
    
    37 chars
    2 lines
  2. 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.

  3. Calculate the R2 score using the r2_score function:

    main.py
    r2_score_value = r2_score(y_true, y_pred)
    
    42 chars
    2 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.py
from sklearn.metrics import r2_score

y_true = [3, -0.5, 2, 7]
y_pred = [2.5, 0.0, 2, 8]
r2_score_value = r2_score(y_true, y_pred)

print("R2 Score:", r2_score_value)
167 chars
8 lines

Output:

main.py
R2 Score: 0.9486081370449679
29 chars
2 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.py
pip install scikit-learn
25 chars
2 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