Mi az a korrelációs együttható? Az r értéke a statisztikában megmagyarázva

Az összefüggések remek eszközek annak megismerésére, hogy az egyik dolog hogyan változik a másikkal. Miután elolvasta ezt, meg kell értenie, hogy mi az összefüggés, hogyan kell gondolkodni a korrelációkról a saját munkájában, és kódolnia kell egy minimális megvalósítást a korrelációk kiszámításához.

Összefüggés arról szól, hogy két dolog hogyan változik egymással

A korreláció elvont matematikai fogalom, de valószínűleg már van elképzelése arról, hogy mit jelent. Íme néhány példa a korreláció három általános kategóriájára.

Ha több ételt eszel, akkor valószínűleg jobban érzed magad. Ez egy olyan eset, amikor két dolog ugyanúgy változik együtt. Az egyik felmegy (több ételt eszik), majd a másik is felfelé (jóllakottnak érzi magát). Ez pozitív összefüggés .

Ha autóval ül és gyorsabban halad, akkor valószínűleg gyorsabban eljut az úticéljához, és a teljes utazási ideje kevesebb lesz. Ez két olyan esetről szól, amelyek ellentétes irányban változnak (nagyobb sebesség, de kevesebb idő). Ez negatív összefüggés .

Van egy harmadik lehetséges módja is annak, hogy két dolog "megváltozhat". Vagy inkább nem változtat. Például, ha hízni szeretne, és megnézné, hogyan változtak a teszt eredményei, akkor valószínűleg nem lesz általános változás a teszt eredményeiben. Ez azt jelenti, hogy nincs összefüggés.

A jóslás első lépése annak ismerete, hogy két dolog együtt változik

Nagyszerű, hogy leírhatjuk, mi zajlik az előző példáinkban. De mi értelme van? Ennek oka az, hogy ezeket az ismereteket értelmesen alkalmazzuk, hogy megjósolhassuk, mi fog következni.

Étkezési példánkban feljegyezhetjük, hogy mennyit eszünk egy egész héten keresztül, majd feljegyezhetjük, mennyire érezzük magunkat utólag. Mint azt korábban megállapítottuk, minél többet eszünk, annál jobban érezzük magunkat.

Miután összegyűjtöttük ezeket az információkat, további kérdéseket tehetünk fel arról, miért történik ez, hogy jobban megértsük ezt a kapcsolatot. Itt elkezdhetjük megkérdezni, hogy milyen ételek tesznek teltebbé minket, vagy befolyásolja-e a napszak mennyire érezzük jól magunkat.

Hasonló gondolkodás alkalmazható az Ön munkájára vagy vállalkozására is. Ha azt veszi észre, hogy az értékesítés vagy más fontos mérőszám emelkedik vagy csökken a vállalkozás más mércéjével (más szóval, a dolgok pozitívan vagy negatívan korrelálnak), érdemes lehet feltárni és többet megtudni erről a kapcsolatról, hogy javítsa vállalkozását.

Az összefüggések erőssége különböző lehet

Néhány általános összefüggést is bemutattunk

  • pozitív,
  • negatív, vagy
  • nem létező

Bár ezek a leírások rendben vannak, minden pozitív és negatív összefüggés nem mindegy.

Ezek a leírások számokká is lefordíthatók. A korrelációs érték tetszőleges tizedesértéket vehet fel a negatív, \ (- 1 \) és a pozitív, \ (+ 1 \) között.

A \ (- 1 \) és \ (0 \) közötti tizedesértékek negatív összefüggések, például \ (- 0,32 \).

A \ (0 \) és \ (+ 1 \) közötti tizedesértékek pozitív korrelációk, például \ (+ 0,63 \).

A tökéletes nulla korreláció azt jelenti, hogy nincs korreláció.

Az egyes korrelációs típusokhoz tartozik egy sor erős korreláció és gyenge korreláció. A nullához közelebb eső korrelációs értékek gyengébbek , míg a pozitívhoz vagy negatívhoz közelebb eső értékek erősebbek .

Az erős összefüggések nyilvánvalóbb tendenciákat mutatnak az adatokban, míg a gyengék középszerűbbnek tűnnek. Például az alábbi erősebb magas, pozitív korreláció inkább egy vonalnak tűnik, mint a gyengébb és alacsonyabb, pozitív korreláció.

Példák alacsony, magas és tökéletes pozitív korrelációra x és y között

Hasonlóképpen, az erősen negatív korrelációknak nyilvánvalóbb trendje van, mint a gyengébb és alacsonyabb negatív korrelációnak.

Példák alacsony, magas és tökéletes negatív korrelációkra x és y között

Honnan származik az r érték? És milyen értékeket vehet igénybe?

Az " r érték" a korrelációs érték általános megjelölésének módja. Pontosabban a (minta) Pearson-korrelációra vagy Pearson r- jére utal . A "minta" megjegyzés annak hangsúlyozására szolgál, hogy csak a meglévő adatokra hivatkozhat, és óvatossággal kell eljárnia az adatokon túli nagyobb követelésekkel.

Az alábbi táblázat összefoglalja, hogy mit vizsgáltunk eddig az összefüggésekről.

Pearson r értékeKét dolog közötti összefüggés ...Példa
r = -1Tökéletesen negatívA nap órája és a nap hátralévő óráinak száma
r <0NegatívGyorsabb autósebesség és alacsonyabb utazási idő
r = 0Független vagy nem korreláltSúlygyarapodás és teszteredmények
r> 0PozitívTöbb elfogyasztott étel és jobban érzi magát
r = 1Tökéletesen pozitívNövelje az életkoromat és növelje az életkorát

A következő néhány szakaszban megtesszük

  • A korrelációk kiszámításához bontsa le a matematikai egyenletet
  • Használjon példaszámokat ennek a korrelációs egyenletnek a használatához
  • Kódolja be a matematikai egyenletet Pythonban és JavaScript-ben

A matematika lebontása a korrelációk kiszámításához

Emlékeztetőül: a korrelációk csak \ (- 1 \) és \ (1 \) között lehetnek. Miert van az?

A gyors válasz az, hogy mindkét változóban a változás mértékét egy közös skálához igazítjuk. Technikai szempontból normalizáljuk, hogy a két változó mennyire változik együtt, annyival, hogy a két változó mindegyike önmagában változik.

A Wikipédiából megragadhatjuk a Pearson-korrelációs együttható matematikai meghatározását. Nagyon bonyolultnak tűnik, de bontsuk össze.

\[ \textcolor{lime}{r} _{ \textcolor{#4466ff}{x} \textcolor{fuchsia}{y} } = \frac{ \sum_{i=1}^{n} (x_i - \textcolor{green}{\bar{x}})(y_i - \textcolor{olive}{\bar{y}}) }{ \sqrt{ \sum_{i=1}^{n} (x_i - \textcolor{green}{\bar{x}})^2 \sum_{i=1}^{n} (y_i - \textcolor{olive}{\bar{y}})^2 } }\]

From this equation, to find the \(\textcolor{lime}{\text{correlation}}\) between an \( \textcolor{#4466ff}{\text{x variable}} \) and a \( \textcolor{fuchsia}{\text{y variable}} \), we first need to calculate the \( \textcolor{green}{\text{average value for all the } x \text{ values}} \) and the \( \textcolor{olive}{ \text{average value for all the } y \text{ values}} \).

Let's focus on the top of the equation, also known as the numerator. For each of the \( x\) and \(y\) variables, we'll then need to find the distance of the \(x\) values from the average of \(x\), and do the same subtraction with \(y\).

Intuitively, comparing all these values to the average gives us a target point to see how much change there is in one of the variables.

This is seen in the math form, \(\textcolor{#800080}{\sum_{i=1}^{n}}(\textcolor{#000080}{x_i - \overline{x}})\), \(\textcolor{#800080}{\text{adds up all}}\) the \(\textcolor{#000080}{\text{differences between}}\) your values with the average value for your \(x\) variable.

In the bottom of the equation, also known as the denominator, we do a similar calculation. However, before we add up all of the distances from our values and their averages, we will multiple them by themselves (that's what the \((\ldots)^2\) is doing).

This denominator is what "adjusts" the correlation so that the values are between \(-1\) and \(1\).

Using numbers in our equation to make it real

To demonstrate the math, let's find the correlation between the ages of you and your siblings last year \([1, 2, 6]\) and your ages for this year \([2, 3, 7]\). Note that this is a small example. Typically you would want many more than three samples to have more confidence in your correlation being true.

Looking at the numbers, they appear to increase the same. You may also notice they are the same sequence of numbers but the second set of numbers has one added to it. This is as close to a perfect correlation as we'll get. In other words, we should get an \(r = 1\).

First we need to calculate the averages of each. The average of \([1, 2, 6]\) is \((1+2+6)/3 = 3\) and the average of \([2, 3, 7]\) is \((2+3+7)/3 = 4\). Filling in our equation, we get

\[ r _{ x y } = \frac{ \sum_{i=1}^{n} (x_i - 3)(y_i - 4) }{ \sqrt{ \sum_{i=1}^{n} (x_i - 3)^2 \sum_{i=1}^{n} (y_i - 4)^2 } }\]

Looking at the top of the equation, we need to find the paired differences of \(x\) and \(y\). Remember, the \(\sum\) is the symbol for adding. The top then just becomes

\[ (1-3)(2-4) + (2-3)(3-4) + (6-3)(7-4) \]

\[= (-2)(-2) + (-1)(-1) + (3)(3) \]

\[= 4 + 1 + 9 = 14\]

So the top becomes 14.

\[ r _{ x y } = \frac{ 14 }{ \sqrt{ \sum_{i=1}^{n} (x_i - 3)^2 \sum_{i=1}^{n} (y_i - 4)^2 } }\]

In the bottom of the equation, we need to do some very similar calculations, except focusing on just the \(x\) and \(x\) separately before multiplying.

Let's focus on just \( \sum_{i=1}^n (x_i - 3)^2 \) first. Remember, \(3\) here is the average of all the \(x\) values. This number will change depending on your particular data.

\[ (1-3)^2 + (2-3)^2 + (6-3)^2 \]

\[= (-2)^2 + (-1)^2 + (3)^2 = 4 + 1 + 9 = 14 \]

And now for the \(y\) values.

\[ (2-4)^2 + (3-4)^2 + (7-4)^2 \]

\[ (-2)^2 + (-1)^2 + (3)^2 = 4 + 1 + 9 = 14\]

We those numbers filled out, we can put them back in our equation and solve for our correlation.

\[ r _{ x y } = \frac{ 14 }{ \sqrt{ 14 \times 14 }} = \frac{14}{\sqrt{ 14^2}} = \frac{14}{14} = 1\]

We've successfully confirmed that we get \(r = 1\).

Although this was a simple example, it is always best to use simple examples for demonstration purposes. It shows our equation does indeed work, which will be important when coding it up in the next section.

Python and JavaScript code for the Pearson correlation coefficient

Math can sometimes be too abstract, so let's code this up for you to experiment with. As a reminder, here is the equation we are going to code up.

\[ r _{ x y } = \frac{ \sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y}) }{ \sqrt{ \sum_{i=1}^{n} (x_i - \bar{x})^2 \sum_{i=1}^{n} (y_i - \bar{y})^2 } }\]

After going through the math above and reading the code below, it should be a bit clearer on how everything works together.

Below is the Python version of the Pearson correlation.

import math def pearson(x, y): """ Calculate Pearson correlation coefficent of arrays of equal length. Numerator is sum of the multiplication of (x - x_avg) and (y - y_avg). Denominator is the squart root of the product between the sum of (x - x_avg)^2 and the sum of (y - y_avg)^2. """ n = len(x) idx = range(n) # Averages avg_x = sum(x) / n avg_y = sum(y) / n numerator = sum([(x[i] - avg_x)*(y[i] - avg_y) for i in idx]) denom_x = sum([(x[i] - avg_x)**2 for i in idx]) denom_y = sum([(y[i] - avg_y)**2 for i in idx]) denominator = math.sqrt(denom_x * denom_y) return numerator / denominator

Here's an example of our Python code at work, and we can double check our work using a Pearson correlation function from the SciPy package.

import numpy as np import scipy.stats # Create fake data x = np.arange(5, 15) # array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) y = np.array([24, 0, 58, 26, 82, 89, 90, 90, 36, 56]) # Use a package to calculate Pearson's r # Note: the p variable below is the p-value for the Pearson's r. This tests # how far away our correlation is from zero and has a trend. r, p = scipy.stats.pearsonr(x, y) r # 0.506862548805646 # Use our own function pearson(x, y) # 0.506862548805646

Below is the JavaScript version of the Pearson correlation.

function pearson(x, y) { let n = x.length; let idx = Array.from({length: n}, (x, i) => i); // Averages let avgX = x.reduce((a,b) => a + b) / n; let avgY = y.reduce((a,b) => a + b) / n; let numMult = idx.map(i => (x[i] - avg_x)*(y[i] - avg_y)); let numerator = numMult.reduce((a, b) => a + b); let denomX = idx.map(i => Math.pow((x[i] - avgX), 2)).reduce((a, b) => a + b); let denomY = idx.map(i => Math.pow((y[i] - avgY), 2)).reduce((a, b) => a + b); let denominator = Math.sqrt(denomX * denomY); return numerator / denominator; };

Here's an example of our JavaScript code at work to double check our work.

x = Array.from({length: 10}, (x, i) => i + 5) // Array(10) [ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] y = [24, 0, 58, 26, 82, 89, 90, 90, 36, 56] pearson(x, y) // 0.506862548805646

Feel free to translate the formula into either Python or JavaScript to better understand how it works.

In conclusion

Correlations are a helpful and accessible tool to better understand the relationship between any two numerical measures. It can be thought of as a start for predictive problems or just better understanding your business.

Correlation values, most commonly used as Pearson's r, range from \(-1\) to \(+1\) and can be categorized into negative correlation (\(-1 \lt r \lt 0\)), positive (\(0 \lt r \lt 1\)), and no correlation (\(r = 0\)).

A glimpse into the larger world of correlations

There is more than one way to calculate a correlation. Here we have touched on the case where both variables change at the same way. There are other cases where one variable may change at a different rate, but still have a clear relationship. This gives rise to what's called, non-linear relationships.

Note, correlation does not imply causation. If you need quick examples of why, look no further.

Below is a list of other articles I came across that helped me better understand the correlation coefficient.

  • If you want to explore a great interactive visualization on correlation, take a look at this simple and fantastic site.
  • Using Python, there multiple ways to implement a correlation and there are multiple types of correlation. This excellent tutorial shows great examples of Python code to experiment with yourself.
  • A blog post by Sabatian Sauer goes over correlations using "average deviation rectangles", where each point creates a visual rectangle from each point using the mean, and illustrating it using the R programming language.
  • And for the deeply curious people out there, take a look at this paper showing 13 ways to look at the correlation coefficient (PDF).

Follow me on Twitter and check out my personal blog where I share some other insights and helpful resources for programming, statistics, and machine learning.

Thanks for reading!