查閱
numpy
文檔我們可以看到,
numpy.randn()
,
numpu.random.normal
和
numpu.random.standard_normal()
函數均可用來得到指定個數的高斯分布傳回值。前幾天我突發奇想,有沒有辦法來用他們産生一維高斯分布呢?答案是可以的。
class GaussianDistribution:
@staticmethod
def selfMadeMethod():
num = 1001
array = np.random.randn(num)
max_ = np.max(abs(array))
x = np.linspace(-max_, max_, num)
result = np.ones(num - 1)
for i in range(num):
for j in range(num - 1):
if x[j] < array[i] < x[j + 1]:
result[j] += 1
real_x = np.linspace(-max_ + max_ * 2 / (num - 1), max_ - max_ * 2 / (num - 1), num - 1)
plt.figure(1)
plt.title('1D Gaussian Distribution')
plt.plot(real_x, result)
@staticmethod
def numpyRandomRandn():
num = 1001
array = np.random.randn(num)
plt.figure(2)
plt.title('1D Gaussian Distribution')
plt.hist(array, 50, density=True)
@staticmethod
def numpyRandomNormal():
mu, sigma = 0, 0.1 # mean and standard deviation
s = np.random.normal(mu, sigma, 1000)
plt.figure(3)
plt.title('1D Gaussian Distribution')
plt.hist(s, 50, density=True)
@staticmethod
def numpyRandomStandardNormal():
s = np.random.standard_normal(1000)
plt.figure(4)
plt.title('1D Gaussian Distribution')
plt.hist(s, 50, density=True)
plt.show()
if __name__ == '__main__':
gaussian = GaussianDistribution()
gaussian.selfMadeMethod()
gaussian.numpyRandomRandn()
gaussian.numpyRandomNormal()
gaussian.numpyRandomStandardNormal()
selfMadeMethod()
函數中的方法在某種程度上等同于另外三種方法,四種方法的結果如下圖所示。
selfMadeMethod()
方法結果:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5SO4AjM2MmMkFTY0IGO5U2YyYzX2MDNwgTMzEzLcdDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
我們可以看到,這裡的圖像大概為一個高斯分布型,當然與理想中光滑的曲線有一定的差異,畢竟我們是随機産生高斯分布的數值,推測當随即點數足夠多的時候,曲線會逐漸趨于光滑狀态。然而說明問題就好了,如何優化這裡不做過多讨論。
numpyRandomRandn()
方法結果:
numpyRandomNormal()
方法結果:
numpyRandomStandardNormal()
方法結果: