Skip to content

Instantly share code, notes, and snippets.

@ricardodeazambuja
Forked from benjaminmgross/stats.py
Created January 27, 2019 15:04
Show Gist options
  • Save ricardodeazambuja/82eabaf19280884999ec2487c7c107b5 to your computer and use it in GitHub Desktop.
Save ricardodeazambuja/82eabaf19280884999ec2487c7c107b5 to your computer and use it in GitHub Desktop.
Predicted R-Squared (r2, r^2) Calculation in `python`
def press_statistic(y_true, y_pred, xs):
"""
Calculation of the `Press Statistics <https://www.otexts.org/1580>`_
"""
res = y_pred - y_true
hat = xs.dot(np.linalg.pinv(xs))
den = (1 - np.diagonal(hat))
sqr = np.square(res/den)
return sqr.sum()
def predicted_r2(y_true, y_pred, xs):
"""
Calculation of the `Predicted R-squared <https://rpubs.com/RatherBit/102428>`_
"""
press = press_statistic(y_true=y_true,
y_pred=y_pred,
xs=xs
)
sst = np.square( y_true - y_true.mean() ).sum()
return 1 - press / sst
def r2(y_true, y_pred):
"""
Calculation of the unadjusted r-squared, goodness of fit metric
"""
sse = np.square( y_pred - y_true ).sum()
sst = np.square( y_true - y_true.mean() ).sum()
return 1 - sse/sst
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment