関数でガウス データを生成random.gauss(mu, sigma)
できますが、どうすれば 2D ガウスを生成できますか? そのような機能はありますか?
7 に答える
使えるならnumpy
ありますnumpy.random.multivariate_normal(mean, cov[, size])
。
たとえば、10,000 個の 2D サンプルを取得するには:
np.random.multivariate_normal(mean, cov, 10000)
どこmean.shape==(2,)
とcov.shape==(2,2)
。
指数関数を使用して近似を追加したいと思います。これは、移動可能な対称 2d ガウス分布を含む 2d 行列を直接生成します。
このコードは scipy メーリング リストのアーカイブで見つけて、少し修正したことに注意してください。
import numpy as np
def makeGaussian(size, fwhm = 3, center=None):
""" Make a square gaussian kernel.
size is the length of a side of the square
fwhm is full-width-half-maximum, which
can be thought of as an effective radius.
"""
x = np.arange(0, size, 1, float)
y = x[:,np.newaxis]
if center is None:
x0 = y0 = size // 2
else:
x0 = center[0]
y0 = center[1]
return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / fwhm**2)
参照と機能強化のために、Gist hereとしてホストされています。プルリクエスト大歓迎!
標準の 2D ガウス分布は 2 つの 1D ガウス分布の積に過ぎないため、2 つの軸間に相関関係がない(つまり、共変行列が対角である) 場合は、random.gauss
2 回呼び出すだけです。
def gauss_2d(mu, sigma):
x = random.gauss(mu, sigma)
y = random.gauss(mu, sigma)
return (x, y)
import numpy as np
# define normalized 2D gaussian
def gaus2d(x=0, y=0, mx=0, my=0, sx=1, sy=1):
return 1. / (2. * np.pi * sx * sy) * np.exp(-((x - mx)**2. / (2. * sx**2.) + (y - my)**2. / (2. * sy**2.)))
x = np.linspace(-5, 5)
y = np.linspace(-5, 5)
x, y = np.meshgrid(x, y) # get 2D variables instead of 1D
z = gaus2d(x, y)
2D ガウス関数の簡単な実装と例。ここで、sx と sy は x 方向と y 方向の広がり、mx と my は中心座標です。
Numpy にはこれを行う関数があります。ここに文書化されています。上記で提案された方法に加えて、任意の共分散でサンプルを抽出することができます。
ipython -pylab
が開始されたと仮定した場合の小さな例を次に示します。
samples = multivariate_normal([-0.5, -0.5], [[1, 0],[0, 1]], 1000)
plot(samples[:, 0], samples[:, 1], '.')
samples = multivariate_normal([0.5, 0.5], [[0.1, 0.5],[0.5, 0.6]], 1000)
plot(samples[:, 0], samples[:, 1], '.')
numpy
このメソッドnp.random.normal
を使用して、2D ガウス分布を生成してみることができます。サンプルコードはnp.random.normal(mean, sigma, (num_samples, 2))
.
平均 = 0 およびシグマ 20 を使用して実行したサンプルを以下に示します。
np.random.normal(0, 20, (10,2))
>>array([[ 11.62158316, 3.30702215],
[-18.49936277, -11.23592946],
[ -7.54555371, 14.42238838],
[-14.61531423, -9.2881661 ],
[-30.36890026, -6.2562164 ],
[-27.77763286, -23.56723819],
[-18.18876597, 41.83504042],
[-23.62068377, 21.10615509],
[ 15.48830184, -15.42140269],
[ 19.91510876, 26.88563983]])
したがって、平均 = 0、シグマ = 20 の 2 次元配列で 10 個のサンプルを取得しました。