Book/0005.파이썬으로 배우응 통계학 교과서
[python] 공분산이란? cov
잠수함토끼
2020. 5. 3. 13:59
summary
print('-'*100)
print(sp.cov(x, y, ddof=0))
print(sp.cov(x, y, ddof=1))
공분산
과소하는 경우 N으로 나눠져있다.
cov_sample = sum((x-mu_x)*(y-mu_y))/N
print('{0:.3f}'.format(cov_sample)) #6.906
공분산
과소하는 경우 해결 N-1을 곱함
cov = sum((x-mu_x)*(y-mu_y))/(N-1)
print('{0:.3f}'.format(cov)) # 7.673
full code
from pandas import DataFrame
import pandas as pd
import scipy as sp
import numpy as np
datas:DataFrame = pd.DataFrame({'x':[18.5,18.7,19.1,19.7,21.5,21.7,21.8,22.0,23.4,23.8],
'y':[34, 39, 41, 38, 45, 41, 52, 44, 44, 49]})
print(datas.info())
print(datas.describe())
print(datas)
x = datas['x']
y = datas['y']
print(x)
print(y)
N = len(datas)
mu_x = sp.mean(x)
mu_y = sp.mean(y)
print(mu_x)
print(mu_y)
cov_sample = sum((x-mu_x)*(y-mu_y))/N
print('{0:.3f}'.format(cov_sample))
cov = sum((x-mu_x)*(y-mu_y))/(N-1)
print('{0:.3f}'.format(cov))
분산-공분산 행렬
snippets
print('-'*100)
print(sp.cov(x, y, ddof=0))
print(sp.cov(x, y, ddof=1))
출력 결과
아래와 같이 분산-공분산 행렬을 얻을 수 있다.
[[ 3.2816 6.906 ]
[ 6.906 25.21 ]]
[[ 3.64622222 7.67333333]
[ 7.67333333 28.01111111]]
full code
from pandas import DataFrame
import pandas as pd
import scipy as sp
import numpy as np
datas:DataFrame = pd.DataFrame({'x':[18.5,18.7,19.1,19.7,21.5,21.7,21.8,22.0,23.4,23.8],
'y':[34, 39, 41, 38, 45, 41, 52, 44, 44, 49]})
print(datas.info())
print(datas.describe())
print(datas)
x = datas['x']
y = datas['y']
print(x)
print(y)
N = len(datas)
mu_x = sp.mean(x)
mu_y = sp.mean(y)
print(mu_x)
print(mu_y)
cov_sample = sum((x-mu_x)*(y-mu_y))/N
print('{0:.3f}'.format(cov_sample))
cov = sum((x-mu_x)*(y-mu_y))/(N-1)
print('{0:.3f}'.format(cov))
print('-'*100)
print(sp.cov(x, y, ddof=0))
print(sp.cov(x, y, ddof=1))