LoginSignup
0
0

More than 5 years have passed since last update.

二変量正規分布

Last updated at Posted at 2017-05-04

二変量正規分布を発生させたい

\begin{equation}
  \begin{pmatrix}
    x \\
    y
  \end{pmatrix}
  = N
  \begin{pmatrix}
    \begin{pmatrix}
      \mu_x\\
      \mu_y
    \end{pmatrix}
    _,
    \begin{pmatrix}
      \sigma_x^2 & \rho\sigma_x\sigma_y \\
      \rho\sigma_x\sigma_y & \sigma_y^2 \\
    \end{pmatrix}
  \end{pmatrix}
\end{equation}

まず、$x=N(\mu_x, \sigma_x)$を発生させる。つぎに、xを固定してyを発生させれば良い。この時のyの条件付き分布は

y|x \sim N(\mu_y + \rho\frac{\sigma_y}{\sigma_x}(x-\mu_x), (1-\rho^2)\sigma_y^2))

で与えられる。

pyhonで実装すると

python3
import numpy as np
import matplotlib.pyplot as plt

def MVNORM(mu_x, sigma_x, mu_y, sigma_y, rho, N=1):
  x = np.random.normal(mu_x, sigma_x, N)
  y = np.random.normal(mu_y + rho*sigma_y/sigma_x*(x-mu_x), np.sqrt((1-rho**2)*sigma_y**2), N)
  return([x,y])

#平均0、標準偏差9のxと相関係数0.9で相関のある平均3で標準偏差3のyを1000個発生させる
MV = MVNORM(0, 9, 3, 3, 0.9 ,1000)

plt.scatter(MV[0], MV[1])
plt.show()

SUMMARY = (np.mean(MV[0]), np.std(MV[0]), np.mean(MV[1]), np.std(MV[1]))
print("mean X: {0[0]:0.2f}, stdev X: {0[2]:0.2f}, mean Y: {0[1]:0.2f}, stdev Y: {0[3]:0.2f}".format(SUMMARY))

image

mean X: 0.14, stdev X: 9.09, mean Y: 2.99, stdev Y: 3.08
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0