Pearson's correlation coefficient Return the Pearson's correlation coefficient for two inputs. Pearson's correlation coefficient *r* takes values between -1 and +1. It measures the strength and direction of a linear relationship. >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [9,
(x, y, /, *, method='linear')
| 684 | |
| 685 | |
| 686 | def correlation(x, y, /, *, method='linear'): |
| 687 | """Pearson's correlation coefficient |
| 688 | |
| 689 | Return the Pearson's correlation coefficient for two inputs. Pearson's |
| 690 | correlation coefficient *r* takes values between -1 and +1. It measures |
| 691 | the strength and direction of a linear relationship. |
| 692 | |
| 693 | >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 694 | >>> y = [9, 8, 7, 6, 5, 4, 3, 2, 1] |
| 695 | >>> correlation(x, x) |
| 696 | 1.0 |
| 697 | >>> correlation(x, y) |
| 698 | -1.0 |
| 699 | |
| 700 | If *method* is "ranked", computes Spearman's rank correlation coefficient |
| 701 | for two inputs. The data is replaced by ranks. Ties are averaged |
| 702 | so that equal values receive the same rank. The resulting coefficient |
| 703 | measures the strength of a monotonic relationship. |
| 704 | |
| 705 | Spearman's rank correlation coefficient is appropriate for ordinal |
| 706 | data or for continuous data that doesn't meet the linear proportion |
| 707 | requirement for Pearson's correlation coefficient. |
| 708 | |
| 709 | """ |
| 710 | # https://en.wikipedia.org/wiki/Pearson_correlation_coefficient |
| 711 | # https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient |
| 712 | n = len(x) |
| 713 | if len(y) != n: |
| 714 | raise StatisticsError('correlation requires that both inputs have same number of data points') |
| 715 | if n < 2: |
| 716 | raise StatisticsError('correlation requires at least two data points') |
| 717 | if method not in {'linear', 'ranked'}: |
| 718 | raise ValueError(f'Unknown method: {method!r}') |
| 719 | |
| 720 | if method == 'ranked': |
| 721 | start = (n - 1) / -2 # Center rankings around zero |
| 722 | x = _rank(x, start=start) |
| 723 | y = _rank(y, start=start) |
| 724 | |
| 725 | else: |
| 726 | xbar = fsum(x) / n |
| 727 | ybar = fsum(y) / n |
| 728 | x = [xi - xbar for xi in x] |
| 729 | y = [yi - ybar for yi in y] |
| 730 | |
| 731 | sxy = sumprod(x, y) |
| 732 | sxx = sumprod(x, x) |
| 733 | syy = sumprod(y, y) |
| 734 | |
| 735 | try: |
| 736 | return sxy / _sqrtprod(sxx, syy) |
| 737 | except ZeroDivisionError: |
| 738 | raise StatisticsError('at least one of the inputs is constant') |
| 739 | |
| 740 | |
| 741 | LinearRegression = namedtuple('LinearRegression', ('slope', 'intercept')) |
nothing calls this directly
no test coverage detected
searching dependent graphs…