Correlation in Python

Correlation in Python

Correlation values range between -1 and 1.

There are two key components of a correlation value:

  • magnitude – The larger the magnitude (closer to 1 or -1), the stronger the correlation
  • sign – If negative, there is an inverse correlation. If positive, there is a regular correlation.

Positive Correlation

Let’s take a look at a positive correlation. Numpy implements a corrcoef() function that returns a matrix of correlations of x with x, x with y, y with x and y with y. We’re interested in the values of correlation of x with y (so position (1, 0) or (0, 1)).

import numpy as np

np.random.seed(1)

# 1000 random integers between 0 and 50
x = np.random.randint(0, 50, 1000)

# Positive Correlation with some noise
y = x + np.random.normal(0, 10, 1000)

np.corrcoef(x, y)

Out[1]:

array([[ 1. , 0.81543901],
[ 0.81543901, 1. ]])</pre>

This correlation is 0.815, a strong positive correlation, let’s take a look at a scatter chart.

In [2]:

import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
matplotlib.style.use('ggplot')

plt.scatter(x, y)
plt.show()

[圖片上傳中...(image-3a2a71-1546484758292-4)]

Negative Correlation

What happens to our correlation figure if we invert the correlation such that an increase in x results in a decrease in y?

In [3]:

># 1000 random integers between 0 and 50
x = np.random.randint(0, 50, 1000)

# Negative Correlation with some noise
y = 100 - x + np.random.normal(0, 5, 1000)

np.corrcoef(x, y)

Out[3]:

array([[ 1. , -0.94957116],
[-0.94957116, 1. ]])</pre>

Our correlation is now negative and close to 1. Let’s take a look at what this looks like graphically:

In [4]:

plt.scatter(x, y)
plt.show()

[圖片上傳中...(image-64b86c-1546484758291-3)]

No/Weak Correlatio

What if there is no correlation between x and y?

In [5]:

x = np.random.randint(0, 50, 1000)
y = np.random.randint(0, 50, 1000)

np.corrcoef(x, y)

Out[5]:

array([[ 1. , -0.00554681],
[-0.00554681, 1. ]])
Here we see a very small value for the correlation between x and y, indicating no correlation.

Again, let’s plot this and take a look, we see there is no correlation between x and y:

In [6]:

plt.scatter(x, y)
plt.show()

[圖片上傳中...(image-8ea283-1546484758291-2)]

Correlation Matrix

If we’re using pandas we can create a correlation matrix to view the correlations between different variables in a dataframe:

In [7]:

import pandas as pd

df = pd.DataFrame({'a': np.random.randint(0, 50, 1000)})
df['b'] = df['a'] + np.random.normal(0, 10, 1000) # positively correlated with 'a'
df['c'] = 100 - df['a'] + np.random.normal(0, 5, 1000) # negatively correlated with 'a'
df['d'] = np.random.randint(0, 50, 1000) # not correlated with 'a'

df.corr()

Out[7]:

a b c d
a 1.000000 0.825361 -0.948845 0.009802
b 0.825361 1.000000 -0.789391 0.011852
c -0.948845 -0.789391 1.000000 -0.003228
d 0.009802 0.011852 -0.003228 1.000000

We can also view these correlations graphically as a scatter matrix:

In [8]:

pd.scatter_matrix(df, figsize=(6, 6))
plt.show()

[圖片上傳中...(image-b6224b-1546484758291-1)]

Or we can directly plot a correlation matrix plot:

In [9]:

plt.matshow(df.corr())
plt.xticks(range(len(df.columns)), df.columns)
plt.yticks(range(len(df.columns)), df.columns)
plt.colorbar()
plt.show()

[圖片上傳中...(image-b20b7a-1546484758291-0)]

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末混弥,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌日缨,老刑警劉巖浴麻,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡十性,警方通過查閱死者的電腦和手機限佩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門葵诈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人祟同,你說我怎么就攤上這事作喘。” “怎么了晕城?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵泞坦,是天一觀的道長。 經(jīng)常有香客問我广辰,道長暇矫,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任择吊,我火速辦了婚禮李根,結果婚禮上,老公的妹妹穿的比我還像新娘几睛。我一直安慰自己房轿,他們只是感情好,可當我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布所森。 她就那樣靜靜地躺著囱持,像睡著了一般。 火紅的嫁衣襯著肌膚如雪焕济。 梳的紋絲不亂的頭發(fā)上纷妆,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天,我揣著相機與錄音晴弃,去河邊找鬼掩幢。 笑死逊拍,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的际邻。 我是一名探鬼主播芯丧,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼世曾!你這毒婦竟也來了缨恒?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤轮听,失蹤者是張志新(化名)和其女友劉穎骗露,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蕊程,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡椒袍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了藻茂。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片驹暑。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖辨赐,靈堂內(nèi)的尸體忽然破棺而出优俘,到底是詐尸還是另有隱情,我是刑警寧澤掀序,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布帆焕,位于F島的核電站,受9級特大地震影響不恭,放射性物質(zhì)發(fā)生泄漏叶雹。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一换吧、第九天 我趴在偏房一處隱蔽的房頂上張望折晦。 院中可真熱鬧,春花似錦沾瓦、人聲如沸满着。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽风喇。三九已至,卻和暖如春缕探,著一層夾襖步出監(jiān)牢的瞬間魂莫,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工爹耗, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留耙考,地道東北人秽誊。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像琳骡,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子讼溺,可洞房花燭夜當晚...
    茶點故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 字符串 1.什么是字符串 使用單引號或者雙引號括起來的字符集就是字符串楣号。 引號中單獨的符號、數(shù)字怒坯、字母等叫字符炫狱。 ...
    mango_2e17閱讀 7,510評論 1 7
  • 《閉上眼睛才能看清楚自己》這本書是香海禪寺主持賢宗法師的人生體悟,修行心得及講學錄剔猿,此書從六個章節(jié)講述了禪修是什么...
    宜均閱讀 10,028評論 1 25
  • 前言 Google Play應用市場對于應用的targetSdkVersion有了更為嚴格的要求视译。從 2018 年...
    申國駿閱讀 64,234評論 14 98
  • 第七章:理性的投資觀 字數(shù): 1.投資要圍繞目的進行 投資的目的是為了掙錢。投資的除了金錢還有時間和精力也是一種投...
    幸福萍寶閱讀 3,326評論 1 2
  • 本文轉載自微信公眾號“電子搬磚師”归敬,原文鏈接 這篇文章會以特別形象通俗的方式講講什么是PID酷含。 很多人看到網(wǎng)上寫的...
    這個飛宏不太冷閱讀 6,846評論 2 15