%matplotlib inline
from ipywidgets import *
import matplotlib.pyplot as plt
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('svg')
import numpy as np
import scipy.stats as stats
def corr_plot(slope=1, sd=0, typ='kowariancja', show=False):
x = np.linspace(0, 10, 100)
y = slope * x + np.random.normal(0,sd,100)
fig, axes = plt.subplots(figsize=(6,6))
plt.scatter(x, y)
c = np.corrcoef(x, y)[0][1] if typ=="korelacja" else np.cov(x,y)[0][1]
c = round(c,3)
title = "c="+str(c) if typ=='kowariancja' else "r="+str(c)
if show:
plt.title(title)
plt.xlim(0,10)
plt.ylim(-10,10)
def corr_examples(example="1", typ='kowariancja', show=False):
x = np.linspace(1, 10, 100)
y = -x**3 + np.random.normal(0,100,100) if example=="1" else np.cos(x) + np.random.normal(0,0.1,100)
plt.scatter(x, y)
if show:
if typ=="korelacja":
plt.title("r="+str(round(np.corrcoef(x, y)[0][1],3)))
else:
plt.title("c="+str(round(np.cov(x, y)[0][1],3)))
Przykład:
X | Y |
---|---|
1 | 5 |
2 | 6 |
3 | 1 |
mx = 2
my = 4
((1-2)(5-4)+(2-2)(6-4)+(3-2)(1-4))/2 = (-1+0-3)/2 = -2
interact(corr_plot, slope=(-1, 1, 0.1), sd=(0,10,1), typ=["kowariancja", "korelacja"])
interact(corr_examples, typ=["kowariancja", "korelacja"], example=["1", "2"])
$\;\;\;\;\;E[(X-\mu_x)(Y-\mu_y)] = E[XY - X\mu_Y-Y\mu_X+\mu_X\mu_Y]=E[XY]-E[X\mu_Y]-E[Y\mu_X]+\mu_X\mu_Y=E[XY]-\mu_X\mu_Y$
Przykład c.d.:
$S_X$ = 1
$S_Y$ = 2.646
$r = \frac{-2}{1*2.646} = -0.76$
interact(corr_plot, slope=(-1, 1, 0.1), sd=(0,10,1), typ=["kowariancja", "korelacja"])
interact(corr_examples, typ=["kowariancja", "korelacja"], example=["1", "2"])
$\;\;\;\;\;\;H_0: \rho=0$
$\;\;\;\;\;\;H_1: \rho > / \neq / < 0$
interact(corr_plot, slope=(-1, 1, 0.1), sd=(0,10,1), typ=["kowariancja", "korelacja"])
$Y = \hat{Y} + \epsilon$
$Y=\beta_0+\beta_1X+\epsilon$
Założenia:
$Y=b_0+b_1X+e$
$\hat{Y}=b_0+b_1X$
$e_i=y_i-\hat{y_i}$
prosta regresji przechodzi przez $(\bar{x}, \bar{y})$
znak($b_1$) = znak($r$)
Przykład c.d. 2:
b1 = -2/1 = -2
b0 = 4 + 4 = 8
x = np.array([1,2,3])
y = np.array([5,6,1])
plt.scatter(x, y)
a = -2
b = 8
plt.plot(x, x*a+b)