forked from h2oai/driverlessai-recipes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pearson_correlation.py
32 lines (27 loc) · 1.08 KB
/
pearson_correlation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"""Pearson Correlation Coefficient for regression"""
import typing
import numpy as np
from h2oaicore.metrics import CustomScorer
class Pearson_Correlation(CustomScorer):
_description = "Pearson Correlation coefficient"
_regression = True
_maximize = True
_perfect_score = 1.
_display_name = "PearsonR"
def score(self,
actual: np.array,
predicted: np.array,
sample_weight: typing.Optional[np.array] = None,
labels: typing.Optional[np.array] = None,
**kwargs) -> float:
if sample_weight is None:
sample_weight = np.ones(actual.shape[0])
sx = np.sum(predicted * sample_weight)
sy = np.sum(actual * sample_weight)
sx_2 = np.sum(predicted * predicted * sample_weight)
sy_2 = np.sum(actual * actual * sample_weight)
sxy = np.sum(predicted * actual * sample_weight)
n = np.sum(sample_weight)
sq = np.sqrt(np.abs(n * sx_2 - (sx * sx)) * np.abs(n * sy_2 - (sy * sy)))
cor = (n * sxy - sx * sy) / max(sq, 1E-30)
return cor