LoginSignup
1
2

More than 1 year has passed since last update.

はじめに

データ分析において、任意の正規分布データを作る方法を紹介する。

やりたいこと

このようなデータを作りたい。
Figure_2.png

1次元の正規分布を二つ合わせてみる。

まず、X1の正規分布のデータを作成する。
同様にX2の正規分布のデータを作成する。
X1, X2を合わせて、プロットしてみる。

import numpy as np
import matplotlib.pyplot as plt

# 01.1次元データを別々に作る。

x1 = np.random.normal(loc=10, scale=50, size=1000) #loc :mean, scale : stdev
x2 = np.random.normal(loc =20, scale=10, size=1000)

#plot

fig, ax1 = plt.subplots()
ax1.scatter(x1, x2)
ax1.set_title('toy_data')
ax1.set_xlabel('x1')
ax1.set_ylabel('x2')
ax1.set_aspect('equal')
ax1.grid()

グラフに書いてみると、(当たり前ですが)X1とX2の相関がないグラフが出来てしまう。
これでは、多変量分析には使えないため、次の方法に移す。

Figure_1.png

念のため、X1, X2の相関係数と、分散・共分散行列を計算してみる。

correlation = np.corrcoef(x1,x2)
print('相関係数', correlation)

covariance = np.cov(x1, x2)
print('分散・共分散行列',covariance)

結果
相関係数 
[[ 1.        -0.0434849]
 [-0.0434849  1.       ]]

分散共分散行列 
[[2633.79021587  -23.18642097]
 [ -23.18642097  107.94668376]]

計算結果はやはりである。

2次元の正規分布を作る。

2次元の正規分布を作る時、下記の二つのパラメータを指定する必要がある。(当然)

  1. 各変数の平均
  2. 変数群の分散・共分散行列
#平均
mu1 = 10
mu2 = 20
mean_mat = np.array([mu1, mu2])

#分散/共分散行列
var1 = 20
var2 = 20
cov_12 = 25#[-inf, inf]

cov_mat = np.array([[var1, cov_12],
                    [cov_12, var2]])

print(cov_mat)

結果
[[20 25]
 [25 20]]

次に下記のコードでデータを作る。


X = np.random.multivariate_normal(mean=mean_mat, cov=cov_mat, size=1000)
print(X.shape)
print(X.T.shape)

結果
X.shape  (1000, 2)
X.T.shape  (2, 1000)

可視化してみる。

fig2, ax1 = plt.subplots()
ax1.scatter(X.T[0], X.T[1])
ax1.set_title('toy_data')
ax1.set_xlabel('x1')
ax1.set_ylabel('x2')
ax1.set_aspect('equal')
ax1.grid()

期待した通りの結果で満足。

Figure_2.png

結論

今後、
np.random.multivariate_normal()
を活用する。

おまけ(3次元)

3次元のデータは下記の式で作成する。n次元も基本的に同じ方法で作成可能である。

# 3次元の正規分布からデータセットを作成する
#平均と分散/共分散行列を与え、正規分布を作る。

#平均
mu11 = 10
mu22 = 20
mu33 = 30
mean_mat = np.array([mu11, mu22, mu33])

#分散/共分散行列
var11 = 10
var22 = 10
var33 = 10

cov_12 = 0 #[-inf, inf]
cov_23 = 0
cov_13 = 0
cov_mat = np.array([[var11, cov_12, cov_13],
                    [cov_12, var22, cov_23],
                    [cov_13, cov_23, var33]])


#分布を作る
X = np.random.multivariate_normal(mean=mean_mat, cov=cov_mat, size=1000)


```python
print(X.shape)
print(X.T.shape)


fig3 = plt.figure()
ax1 = fig3.add_subplot(111, projection='3d')

ax1.scatter3D(X.T[0], X.T[1], X.T[2])
ax1.set_title('toy_data')
ax1.set_xlabel('x1')
ax1.set_ylabel('x2')
ax1.set_ylabel('x3')
#ax1.set_aspect('equal')
ax1.grid()

plt.show()
X.shape (1000, 3)
X.T.shape (3, 1000)

Figure_3.png

1
2
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
1
2