확률변수란?
주사위 던졌을 때 3이 나올 확률을 P[X=3] = 1/6, 또는 사람의 몸무게가 70kg 일 확률밀도를 p(X=70) = 0.032 로 표현할 때, 이처럼 시행 결과 하나 하나를 수치로 대응시키는 X를 확률변수' 혹은 '랜덤변수(random variables)'라 정의한다.
랜덤변수 X 는 이와 같이 시행 결과 s를 실수치 X(s) 로 대응시키는 함수로서, 샘플공간의 모든 요소들을 실수(또는 실선)에 매핑을 수행하게 된다.
확률 분포란?
ex1) 두 개의 동전을 던지는 확률 실험에서 앞면이 나오는 숫자의 (이산)확률분포
x | 0 | 1 | 2 |
---|---|---|---|
P[X=x] | 1/4 | 1/2 | 1/4 |
ex2) 두 개의 주사위를 던져서 나오는 점들의 합의 (이산)확률분포
y | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
---|---|---|---|---|---|---|---|---|---|---|---|
P[Y=y] | 1/36 | 2/36 | 3/36 | 4/36 | 5/36 | 6/36 | 5/36 | 4/36 | 3/36 | 2/36 | 1/36 |
누적분포함수
확률변수 X의 누적분포함수 (cumulative distribution function; cdf) $F_X(x)$는 확률변수 $X$ 가 $\{X ≤ x\}$ 일 확률함수이다.
$$F_X(x) = P[X \le x] \quad \text{for } -\infty < x < \infty$$누적분포함수의 성질
$$ 0 \le F_X(x) \le 1 $$$$ \lim_{x \rightarrow \infty} F_X(x) = 1 $$$$ \lim_{x \rightarrow -\infty} F_X(x) = 0 $$$$ F_X(a) \le F_X(b) \text{ if } a \le b $$확률밀도함수 / 확률질량함수
확률변수 X의 확률밀도함수(probability density function; pdf) $f_X(x)$ 는 연속확률변수 X 의 누적분포 $F_X(x)$ 의 미분값으로 정의한다.
$$ f_X(x) = { dF_X(x) \over dX} $$이산확률변수에서는 확률밀도함수와 동일한 개념으로 누적분포 $F_X(x)$ 의 차분값으로 정의하며, 이를 특별히 확률질량함수(probability mass function, pmf) 라고 한다.
$$ f_X(x) = {\Delta F_X(x) \over \Delta X} $$확률밀도함수의 성질
$$ f_X(x) \ge 0 $$$$ P[ a < x < b ] = \int_a^b f_X(x) dx $$$$ F_X(x) = \int_{-\infty}^x f_X(x) dx $$$$ 1 = \int_{-\infty}^{+\infty} f_X(x) dx $$$$ f_X(x|A) = {d \over dx} F_X(x|A) \quad \text{where } F_X(x|A) = { P[\{X<x\}\cap A] \over P[A] } \text{ if } P[A] > 0 $$확률밀도함수는 확률의 밀도를 정의하는 것이므로, 실제 확률을 얻기 위해서는 확률밀도함수를 일정구간에서 적분하여야 함.
확률질량함수는 실제확률을 나타냄.
확률변수의 기대값/평균 :
따라서, 일반 데이타에 대한 평균 $\bar{x}$ 과 분산 $s^2$ 을 구별하기 위해서 모집단의 평균은 $\mu$(mu)로, 분산은 $\sigma^2$(sigma square) 로 사용한다.
$$ \bar{x} = { 1 \over n } \sum_{i=1}^n x_i = { 1 \over n } \sum_{all x} n_x x = { 1 \over n } \sum_{all x} x { n_x \over n} $$여기에서 ${ n_x / n}$ 는 상대도수 ($n_x$는 x값을 갖는 자료점의 수)
$n$ 값을 증가시키면 상대도수 ${n_x / n}$ 는 통계적 확률, 즉 근사확률 $p(x)$ 에 접근하게 된다. 그러므로 다음과 같이 되고,
$$ E[x] = \mu = \sum_{all x} x p(x) $$이 식을 $x$ 의 기대값(expectation)이라고 한다. 이는 각 값의 가중 산술평균을 확률적 용어로 표현한 것인데, 어떤 실험을 무수히 반복했을 때 예상되는 평균 값을 말하며, 연속확률변수인 경우에는 다음과 같이 표현된다.
$$ E[X] = \mu = \int_{-\infty}^{\infty} x f_X(x) dx$$확률변수의 분산:
이산 자료 샘플의 분산 $$ s^2 = { 1 \over n} \sum_{i=1}^n (x_i - \bar{x})^2 = \sum_{all x} (x - \bar{x})^2 { n_x \over n}$$
여기에서 ${ n_x / n}$ 는 상대도수이다. 이산 자료의 모집단 분산은 $n$ 값을 증가시키면 상대도수 ${n_x / n}$ 는 통계적 확률, 즉 근사확률 $p(x)$ 에 접근하게 되고, 평균 $\bar{x}$ 대신에 기대값 $\mu$ 와 함께 다음과 같이 된다.
$$ \sigma^2 = \sum_{all x} (x - \mu)^2 p(x)$$연속 자료의 모집단 분산은 자료들의 합 대신에 적분으로 표현되어 다음과 같이 된다.
$$Var[X] = E[(X-E[X])^2] = \int_{-\infty}^{\infty} (x - \mu)^2 f_X(x)dx $$벡터 랜덤변수
확률 변수를 2개 이상 고려한 경우로 확률변수의 개념을 확장한 것으로 열(column)벡터로 정의된다. 2개의 랜덤변수를 고려한 경우를 이중(binary) 랜덤변수라고 한다. 즉, 표본 공간 $S$ 에서 정의되는 두 개의 랜덤변수 $X, Y$ 를 고려할 경우에 두 개의 랜덤 벡터는 각각 $x, y$ 라는 값을 가지며 순서쌍 $(x, y)$ 로 표현되는 새로운 표본 공간 (이를 결합 표본공간이라고 한다)의 $xy$ 평면상의 임의의 점(random point)에 대응될 것이다. 그리고 누적분포함수와 확률밀도함수 개념은 "결합 누적분포함수(joint cdf)"와 "결합 확률밀도함수(joint pdf)"로 확장된다.
결합 누적분포함수 (Joint Cumulative Density Function; Joint cdf)
$$ F_X(x) = P_X[\{X_1 \le x_1\} \cap \{X_2 \le x_2\} \cap \cdots \cap \{X_N \le x_N\} ]$$결합 확률밀도함수 (Joint Probability Density Function; Joint pdf)
$$ f_X(x) = { \partial^N F_X(x) \over \partial x_1 \partial x_2 \cdots \partial x_N } $$랜덤 벡터의 통계적 특징은 결합 누적분포함수(joint cdf) 혹은 결합 확률밀도함수(joint pdf) 를 이용하여 정의할 수 있다. 또한 랜덤 벡터를 스칼라 확률변수에서 정의한 것과 같은 방식으로 표현할 수 있다.
두 확률변수 $X$ 와 $Y$ 의 공분산은 기대값 연산자를 사용하여 다음과 같이 정의된다.
$$ \Sigma = E[(X-\mu) (X-\mu)^T ] = E[XX^T] - \mu \mu^T = S - \mu \mu^T$$여기에서 $S$는 자기상관행렬로 다음과 같다.
$$ S = E[XX^T] = \begin{bmatrix} E[x_1x_1] & \cdots & E[x_1x_N] \\ \cdots & \ddots & \cdots \\ E[x_Nx_1] & \cdots & E[x_Nx_N] \\ \end{bmatrix} $$그리고,
$$ \Sigma = \Gamma R \Gamma = \begin{bmatrix} \sigma_1 & 0 & \cdots & 0 \\ 0 & \sigma_2 & & \\ \cdots & & \cdots & \\ 0 & & & \sigma_N \\ \end{bmatrix} \begin{bmatrix} 1 & \rho_{12} & \cdots & \rho_{1N} \\ \rho_{12} & 1 & & \\ \cdots & & \cdots & \\ \rho_{1N} & & & 1 \\ \end{bmatrix} \begin{bmatrix} \sigma_1 & 0 & \cdots & 0 \\ 0 & \sigma_2 & & \\ \cdots & & \cdots & \\ 0 & & & \sigma_N \\ \end{bmatrix} $$$\Gamma$가 특징들의 스칼라를 포함하고, $R$은 특징들 간의 근본적인 관계정보를 보유하고 있으 므로 편리한 수식 표현이다. $R$은 상관행렬(correlation matrix)이다.
이산확률변수의 공분산 항은 다음과 같이 표현 될 수 있다. $c_{ii} = \sigma_i^2$ 이고, $c_{ik} = \rho_{ik} \sigma_i \sigma_k$, 여기에서 $\rho_{ik}$를 상관계수(correlation coefficient)라 한다.
확률변수의 상관계수는 다음과 같은 성질을 가진다.
$$−1 \le \rho \le 1 $$또한 $\rho$ 가 $-1, 0, 1$인 경우를 각각 다음과 같이 부른다.
이 상관계수의 부호와 크기가 의미하는 바는 다음 스캐터 플롯에서 알 수 있다. 이 스캐터 플롯은 특정한 상관계수를 가지는 데이터를 시뮬레이션을 통해 그린 것이다. 스캐터 플롯의 위에 쓰여진 숫자는 시뮬레이션에 사용된 상관계수를 나타낸다. 스캐터 플롯의 데이터가 양의 기울기를 가지는 직선 혹은 타원 모양을 가지면 상관계수는 양수이고 음의 기울기를 가지는 직선 혹은 타원 모양이 되면 상관계수가 음이 된다. 또한 직선 모양이 뚜렷할수록 상관계수의 절대값이 커지고 원에 가까워질 수록 절대값이 작아진다.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
corrs = [-1, -0.7, -0.3, 0, 0.3, 0.7, 1]
plt.figure(figsize=(len(corrs), 2))
for i, r in enumerate(corrs):
x, y = np.random.multivariate_normal([0, 0], [[1, r], [r, 1]], 500).T
plt.subplot(1, len(corrs), i + 1)
plt.plot(x, y, 'ro', ms=1)
plt.axis('equal')
plt.xticks([])
plt.yticks([])
plt.title(r"$\rho$={}".format(r))
plt.suptitle("Correlation coefficients and the shape of scatter plots", y=1.1)
plt.tight_layout()
plt.show()
다음과 같이 3차원 분포의 표본이 주어진 경우, 공분산 행렬과 모든 변수 쌍에 대한 분산플롯을 완성하시오.
Examples | $X_1$ | $X_2$ | $X_3$ |
---|---|---|---|
1 | 2 | 2 | 4 |
2 | 3 | 4 | 6 |
3 | 5 | 4 | 2 |
4 | 6 | 6 | 4 |
X = np.array([[2,3,5,6],[2,4,4,6],[4,6,2,4]])
print("Covariance Matrix \n", np.cov(X, ddof=0))
print("Correlation Coefficient \n", np.corrcoef(X))
fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
fig.suptitle('Scatter plots for each different pair ')
ax1.scatter(X[0,:],X[1,:])
ax1.set_xlim(-2,10)
ax1.set_ylim(1,8)
ax1.set_title("x1 vs. x2")
ax2.scatter(X[1,:],X[2,:])
ax2.set_xlim(-2,10)
ax2.set_ylim(1,8)
ax2.set_title("x2 vs. x3")
ax3.scatter(X[2,:],X[0,:])
ax3.set_xlim(-2,10)
ax3.set_ylim(1,8)
ax3.set_title("x3 vs. x1")
plt.show()
Covariance Matrix [[ 2.5 2. -1. ] [ 2. 2. 0. ] [-1. 0. 2. ]] Correlation Coefficient [[ 1. 0.89442719 -0.4472136 ] [ 0.89442719 1. 0. ] [-0.4472136 0. 1. ]]
X = np.array([[2,3,5,6],[2,4,4,6],[4,6,2,4]])
X_mean = np.mean(X, axis=1)
print("Mean ", X_mean)
X_diff = (X.T - X_mean).T
print("difference \n", X_diff)
X_cov = np.dot(X_diff, X_diff.T) / 4
print("covariance matrix \n", X_cov)
Mean [4. 4. 4.] difference [[-2. -1. 1. 2.] [-2. 0. 0. 2.] [ 0. 2. -2. 0.]] covariance matrix [[ 2.5 2. -1. ] [ 2. 2. 0. ] [-1. 0. 2. ]]
확률 이론에서 가우시안 (또는 정규) 분포는 매우 일반적인 연속 확률 분포입니다. 정규 분포는 통계에서 중요하며, 분포가 알려지지 않은 실제 값의 랜덤 변수를 나타 내기 위해 자연 및 사회 과학에서 종종 사용됩니다.
여기에서 $\sigma$ 는 표준편차를, $\mu$는 기대값을, exp[ ] 는 Euler's number : e = 2.7182818284.. 의 지수함수를 각각 나타낸다.
$$ f(x;\mu=0, \sigma^2=1) = { 1 \over \sqrt{2 \pi} 1 } \exp \left[-{1 \over 2} \left({x \over 1}\right)^2\right] = \mathscr{N}(\mu=0, \sigma^2=1)$$$$ f(x;\mu=0, \sigma^2=4) = { 1 \over \sqrt{2 \pi} 4 } \exp \left[-{1 \over 2} \left({x \over 2}\right)^2\right] = \mathscr{N}(\mu=0, \sigma^2=4)$$$$ f(x;\mu=2, \sigma^2=9) = { 1 \over \sqrt{2 \pi} 3 } \exp \left[-{1 \over 2} \left({x-2 \over 3}\right)^2\right] = \mathscr{N}(\mu=2, \sigma^2=9)$$import numpy as np
import matplotlib.pyplot as plt
def np_gaussian_pdf(domain, mu, sigma, sample=0.2):
X = np.arange(-domain+mu, domain+mu, sample)
Z = ((1. /(sigma * np.sqrt(2 * np.pi))) * np.exp(-.5*((X-mu)/sigma)**2))
return X, Z
plt.plot(*np_gaussian_pdf(10, 0, 1, 0.2), label="mu=0, sigma=1")
plt.plot(*np_gaussian_pdf(10, 0, 2, 0.2), label="mu=0, sigma=2")
plt.plot(*np_gaussian_pdf(10, 2, 3, 0.2), label="mu=2, sigma=3")
plt.xlabel('x', fontsize=14)
plt.ylabel('f(x)', fontsize=14)
plt.legend()
<matplotlib.legend.Legend at 0x7fbeac343400>
import scipy as sp
from scipy import stats
xx = np.linspace(-10, 10, 100)
mu = 0
std = 1
rv = sp.stats.norm(mu, std)
plt.plot(xx, rv.pdf(xx), label="mu=0, sigma=1")
rv = sp.stats.norm(0, 2)
plt.plot(xx, rv.pdf(xx), label="mu=0, sigma=2")
rv = sp.stats.norm(2, 3)
plt.plot(xx, rv.pdf(xx), label="mu=2, sigma=3")
plt.xlabel('x')
plt.ylabel("f(x)")
plt.title("pdf of normal distribution")
plt.legend()
plt.show()
D 차원 다변량 가우시안 정규 분포(MVN: multivariate Gaussian normal distribution)의 확률밀도함수는 평균 벡터 $\mu$ 와 공분산 행렬 $\Sigma$ 라는 두 개의 모수를 가지며 다음과 같은 수식으로 정의된다.
$$ \mathscr{N}(\mathbf{x};\mu, \Sigma) = { 1 \over(2 \pi)^{D/2} | \Sigma |^{1/2} } \exp \left[-{1 \over 2} (\mathbf{x} -\mathbf{\mu})^T \Sigma^{-1} (\mathbf{x}-\mathbf{\mu}) \right]$$이 식에서 각 기호의 의미는 다음과 같다.
다변량 가우시안 정규분포에서 공분산 행렬은 일반적으로 양의 정부호 대칭행렬(positive definite symmetric matrix)만 다룬다.
$$ f\left( \begin{bmatrix} x_1 \\ x_2 \end{bmatrix}; \mu=\begin{bmatrix} 1 \\ 2 \end{bmatrix}, \Sigma = \begin{bmatrix} 2 & 0 \\ 0 & 4 \end{bmatrix} \right) = { 1 \over \sqrt{(2 \pi)^2} \sqrt{8} } \exp \left[-{1 \over 2} [ x_1-1, x_2-2] \begin{bmatrix} 0.5 & 0 \\ 0 & 0.25 \end{bmatrix} \begin{bmatrix} x_1-1 \\ x_2-2 \end{bmatrix} \right]$$$$ f\left( \begin{bmatrix} x_1 \\ x_2 \end{bmatrix}; \mu=\begin{bmatrix} 5 \\ 9 \end{bmatrix}, \Sigma = \begin{bmatrix} 1 & 2 \\ 2 & 8 \end{bmatrix} \right) = { 1 \over \sqrt{(2 \pi)^2} 2 } \exp \left[-{1 \over 2} [ x_1-5, x_2-9] \begin{bmatrix} 2 & 0.5 \\ 0.5 & 0.25 \end{bmatrix} \begin{bmatrix} x_1-5 \\ x_2-9 \end{bmatrix} \right]$$from mpl_toolkits import mplot3d
fig = plt.figure()
ax = plt.axes(projection='3d')
# Make data.
X = np.arange(0, 10, 0.2)
Y = np.arange(0, 20, 0.2)
X, Y = np.meshgrid(X, Y)
mu = [5, 9]
cov = [[1, 2], [2, 8]]
rv = sp.stats.multivariate_normal(mu, cov)
Z = rv.pdf(np.dstack([X, Y]))
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap='coolwarm')
ax.set_zlim(0, 0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
mu = [5, 9]
cov = [[1, 2], [2, 8]]
x = np.random.multivariate_normal(mu, cov, (50,50))
plt.scatter(x[:,:,0], x[:,:,1], s=1)
plt.show()
중심 극한 정리 (central Limit Theorem) : 평균 $\mu$ 와 분산 $\sigma^2$ 를 갖는 경우 평균의 표본 분포는 표본의 크기($N$)가 증가함에 따라, 평균 $\mu$ 와 분산 $\sigma^2 /N$을 갖는 정규분포로 접 근한다.
균등 분포(uniform distribution)의 자료로부터 500번의 실험을 수행한 경우
기 시작함)
** 다변량 가우시안 분포의 예 (구형 공분산)**
2차원($D=2$) 다변량 정규분포의 예를 몇가지 살펴보자. 우선 2차원이므로 확률 변수 벡터는 $$ x = \begin{bmatrix}x_1 \\ x_2 \end{bmatrix} $$ 이다.
만약 $$ \mu = \begin{bmatrix}2 \\ 3 \end{bmatrix}. \;\;\; \Sigma = \begin{bmatrix}1 & 0 \\ 0 & 1 \end{bmatrix} $$
이면
$$ | \Sigma| = 1. \;\;\; \Sigma^{-1} = \begin{bmatrix}1 & 0 \\ 0 & 1 \end{bmatrix} $$$$ (x-\mu)^T \Sigma^{-1} (x-\mu) = \begin{bmatrix}x_1 - 2 & x_2 - 3 \end{bmatrix} \begin{bmatrix}1 & 0 \\ 0 & 1 \end{bmatrix} \begin{bmatrix}x_1 - 2 \\ x_2 - 3 \end{bmatrix} = (x_1 - 2)^2 + (x_2 - 3)^2 $$$$ \mathcal{N}(x_1, x_2) = \dfrac{1}{2\pi} \exp \left( -\dfrac{1}{2} \left( (x_1 - 2)^2 + (x_2 - 3)^2 \right) \right) $$이 확률밀도함수의 모양은 다음과 같다.
SciPy 의 stats 서브패키지에는 다변량 정규분포를 위한 multivariate_normal
명령이 있다. mean
인수로 평균 벡터를, cov
인수로 공분산 행렬을 받는다.
mu = [2, 3]
cov = [[1, 0], [0, 1]]
rv = sp.stats.multivariate_normal(mu, cov)
X = rv.rvs(2000)
xx = np.linspace(-1, 5, 120)
yy = np.linspace(-0, 6, 120)
XX, YY = np.meshgrid(xx, yy)
plt.scatter(X[:, 0], X[:, 1], s=1)
plt.contour(XX, YY, rv.pdf(np.dstack([XX, YY])))
plt.axis("equal") #plt.xlim(-1, 5); plt.ylim(0, 6)
plt.xlabel("$x_1$")
plt.ylabel("$x_2$")
plt.show()
fig = plt.figure()
ax = plt.axes(projection='3d')
# Make data.
X = np.arange(-1, 5, 0.1)
Y = np.arange(-1, 5, 0.1)
X, Y = np.meshgrid(X, Y)
mu = [2, 3]
cov = [[1, 0], [0, 1]]
rv = sp.stats.multivariate_normal(mu, cov)
Z = rv.pdf(np.dstack([X, Y]))
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_zlim(0, 0.3)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
** 다변량 가우시안 분포의 예 (대각 공분산) **
만약 $$ \mu = \begin{bmatrix}0 \\ 0 \end{bmatrix}. \;\;\; \Sigma = \begin{bmatrix}4 & 0 \\ 0 & 1 \end{bmatrix} $$
이면 $$ |\Sigma| = 4,\;\;\; \Sigma^{-1} = \begin{bmatrix}0.25 & 0 \\ 0 & 1 \end{bmatrix} $$
$$ (x-\mu)^T \Sigma^{-1} (x-\mu) = \begin{bmatrix}x_1 & x_2 \end{bmatrix} \begin{bmatrix}0.25 & 0\\ 0 & 1\end{bmatrix} \begin{bmatrix}x_1 \\ x_2 \end{bmatrix} = \dfrac{1}{10}\left(0.25\times x_1^2 + x_2^2\right) $$$$ \mathcal{N}(x_1, x_2) = \dfrac{1}{2\sqrt{5}\pi} \exp \left( -\dfrac{1}{10}\left(7(x_1 - 2)^2 - 6(x_1 - 2)(x_2 - 3) + 2(x_2 - 3)^2\right) \right) $$이 확률밀도함수의 모양은 다음과 같다.
mu = [0, 0]
cov = [[4, 0], [0, 1]]
rv = sp.stats.multivariate_normal(mu, cov)
X = rv.rvs(2000)
xx = np.linspace(-5, 5, 120)
yy = np.linspace(-5, 5, 120)
XX, YY = np.meshgrid(xx, yy)
plt.scatter(X[:, 0], X[:, 1], s=1)
plt.contour(XX, YY, rv.pdf(np.dstack([XX, YY])))
plt.xlabel("$x_1$")
plt.ylabel("$x_2$")
plt.show()
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make data.
X = np.arange(-5, 5, 0.1)
Y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(X, Y)
mu = [0, 0]
cov = [[4, 0], [0, 1]]
rv = sp.stats.multivariate_normal(mu, cov)
Z = rv.pdf(np.dstack([X, Y]))
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap='coolwarm')
# Customize the z axis.
ax.set_zlim(0, 0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
** 다변량 가우시안 분포의 예 (완전 공분산) **
만약 $$ \mu = \begin{bmatrix}2 \\ 3 \end{bmatrix}. \;\;\; \Sigma = \begin{bmatrix}2 & 3 \\ 3 & 7 \end{bmatrix} $$
이면 $$ |\Sigma| = 5,\;\;\; \Sigma^{-1} = \begin{bmatrix}1.4 & -0.6 \\ -0.6 & 0.4 \end{bmatrix} $$
$$ (x-\mu)^T \Sigma^{-1} (x-\mu) = \begin{bmatrix}x_1 - 2 & x_2 - 3 \end{bmatrix} \begin{bmatrix}1.4 & -0.6 \\ -0.6 & 0.4\end{bmatrix} \begin{bmatrix}x_1 - 2 \\ x_2 - 3 \end{bmatrix} = \dfrac{1}{10}\left(14(x_1 - 2)^2 - 12(x_1 - 2)(x_2 - 3) + 4(x_2 - 3)^2\right) $$$$ \mathcal{N}(x_1, x_2) = \dfrac{1}{2\sqrt{5}\pi} \exp \left( -\dfrac{1}{10}\left(7(x_1 - 2)^2 - 6(x_1 - 2)(x_2 - 3) + 2(x_2 - 3)^2\right) \right) $$이 확률밀도함수의 모양은 다음과 같다.
mu = [2, 3]
cov = [[2, 3], [3, 7]]
rv = sp.stats.multivariate_normal(mu, cov)
X = rv.rvs(2000)
xx = np.linspace(-3, 8, 120)
yy = np.linspace(-3, 8, 120)
XX, YY = np.meshgrid(xx, yy)
plt.scatter(X[:, 0], X[:, 1], s=1)
plt.contour(XX, YY, rv.pdf(np.dstack([XX, YY])))
plt.xlabel("$x_1$")
plt.ylabel("$x_2$")
plt.show()
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make data.
X = np.arange(-4, 10, 0.1)
Y = np.arange(-4, 10, 0.1)
X, Y = np.meshgrid(X, Y)
mu = [2, 3]
cov = [[2, 3], [3, 7]]
rv = sp.stats.multivariate_normal(mu, cov)
Z = rv.pdf(np.dstack([X, Y]))
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap='coolwarm')
# Customize the z axis.
ax.set_zlim(0, 0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()