📜  scikit learn r2 score - Python (1)

📅  最后修改于: 2023-12-03 15:19:59.667000             🧑  作者: Mango

Scikit-learn R2 Score - Python

R2 score (also known as coefficient of determination) is a widely-used metric in regression analysis that measures the proportion of variance in the response variable that can be explained by the predictor variables. In Scikit-learn, R2 score can be calculated using the r2_score function provided in the sklearn.metrics module.

Syntax

The syntax for calculating R2 score using the r2_score function is as follows:

from sklearn.metrics import r2_score

r2_score(y_true, y_pred, sample_weight=None, multioutput='uniform_average')
  • y_true: array-like of shape (n_samples, n_outputs) The true values of the response variable.

  • y_pred: array-like of shape (n_samples, n_outputs) The predicted values of the response variable.

  • sample_weight: array-like of shape (n_samples,), default=None Individual weights for each sample.

  • multioutput: string in ['raw_values', 'uniform_average', 'variance_weighted'] or None, default='uniform_average' Defines aggregating of multiple output scores. None means r2_score should return the three values for each dimension of y_true and y_pred.

Example

Here's an example of how r2_score function can be used to calculate R2 score in Python:

from sklearn.metrics import r2_score

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

Output:

0.9486081370449679

In this example, y_true and y_pred are the true and predicted values of the response variable, respectively. The r2_score function returns the R2 score which is equal to 0.9486 (rounded to 4 decimal places).

Conclusion

R2 score is an important metric in regression analysis that measures how well the predictor variables explain the response variable. Scikit-learn provides the r2_score function to calculate R2 score in Python.