如何从Python的对数正态分布生成随机数?
对数通常呈分布的随机变量的连续概率分布在概率论中称为对数正态(或对数正态)分布。
当且仅当 log(x) 服从正态分布时,才称变量 x 服从对数正态分布。 PDF 定义如下。
其中 mu 是总体均值,sigma 是变量对数正态分布的标准差。正如正态分布是大量独立同分布随机变量相加的表现,对数正态分布是大量独立同分布随机变量相乘的结果。在 NumPy 库的帮助下,从对数正态分布生成随机数非常容易。
句法:
numpy.random.lognormal(mean=0.0, sigma=1.0, size=None)
Parameter:
- mean: It takes the mean value for the underlying normal distribution.
- sigma: It takes only non-negative values for the standard deviation for the underlying normal distribution
- size : It takes either a int or a tuple of given shape. If a single value is passed it returns a single integer as result. If a tuple then it returns a 2D matrix of values from log-normal distribution.
Returns: Drawn samples from the parameterized log-normal distribution(nd Array or a scalar).
下面的示例描述了如何从对数正态分布生成随机数:
Python3
# import modules
import numpy as np
import matplotlib.pyplot as plt
# mean and standard deviation
mu, sigma = 3., 1.
s = np.random.lognormal(mu, sigma, 10000)
# depict illustration
count, bins, ignored = plt.hist(s, 30,
density=True,
color='green')
x = np.linspace(min(bins),
max(bins), 10000)
pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
/ (x * sigma * np.sqrt(2 * np.pi)))
# assign other attributes
plt.plot(x, pdf, color='black')
plt.grid()
plt.show()
Python3
# Importing required modules
import numpy as np
import matplotlib.pyplot as plt
b = []
# Generating 1000 points from normal distribution.
for i in range(1000):
a = 12. + np.random.standard_normal(100)
b.append(np.product(a))
# Making all negative values into positives
b = np.array(b) / np.min(b)
count, bins, ignored = plt.hist(b, 100,
density=True,
color='green')
sigma = np.std(np.log(b))
mu = np.mean(np.log(b))
# Plotting the graph.
x = np.linspace(min(bins), max(bins), 10000)
pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
/ (x * sigma * np.sqrt(2 * np.pi)))
plt.plot(x, pdf,color='black')
plt.grid()
plt.show()
输出:
让我们证明 log-Normal 是使用Python的随机变量的独立同分布的乘积。在下面的程序中,我们从正态分布中随机生成 1000 个点,然后取它们的乘积,最后绘制它以获得对数正态分布。
蟒蛇3
# Importing required modules
import numpy as np
import matplotlib.pyplot as plt
b = []
# Generating 1000 points from normal distribution.
for i in range(1000):
a = 12. + np.random.standard_normal(100)
b.append(np.product(a))
# Making all negative values into positives
b = np.array(b) / np.min(b)
count, bins, ignored = plt.hist(b, 100,
density=True,
color='green')
sigma = np.std(np.log(b))
mu = np.mean(np.log(b))
# Plotting the graph.
x = np.linspace(min(bins), max(bins), 10000)
pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
/ (x * sigma * np.sqrt(2 * np.pi)))
plt.plot(x, pdf,color='black')
plt.grid()
plt.show()
输出: