在一定范围内的随机数组

时间:2019-04-09 22:53:14

标签: python arrays python-3.x numpy random

我有一个错误为params的数组e_params,并且界限可以为params_bounds

params = [0.2, 0.2]
e_params = [0.1, 0.05]
params_bounds = [(0.0, 1.0), (0.0, 1.0)]

我想画一个params的随机高斯实现,如下所示:

import numpy as np
params_mc = np.random.normal(params, e_params)

有什么方法可以确保结果params_mcparams_bounds指定的上限和下限之内?

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

您可以使用numpy.clip在给定范围内裁剪值。首先生成所需的最小值和最大值的数组,例如:

>>> lower_bound = numpy.asarray(param_bounds)[:, 0]
>>> upper_bound = numpy.asarray(param_bounds)[:, 1]

现在剪辑您的结果:

>>> numpy.clip(params_mc, lower_bound, upper_bound)

(未经测试的代码,您的里程可能会有所不同)

答案 1 :(得分:2)

也许您正在寻找truncated normal distribution。 使用scipy.stats.truncnorm

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

lower, upper = (0.0, 0.0), (1.0, 1.0)
mu, sigma = np.array([0.2, 0.2]), np.array([0.1, 0.05])
X = stats.truncnorm(
    (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)
data = X.rvs((10000, 2))

fig, ax = plt.subplots()
ax.hist(data[:, 0], density=True, alpha=0.5, bins=20)
ax.hist(data[:, 1], density=True, alpha=0.5, bins=20)
plt.show()

收益

enter image description here


这是可视化样品的另一种方法。该代码主要用于from the matplotlib gallery

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

lower, upper = (0.0, 0.0), (1.0, 1.0)
mu, sigma = np.array([0.2, 0.2]), np.array([0.1, 0.05])
X = stats.truncnorm(
    (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)
data = X.rvs((10000, 2))
x, y = data.T

nullfmt = mticker.NullFormatter()         # no labels

# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02

rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]

# start with a rectangular Figure
plt.figure(1, figsize=(8, 8))

axScatter = plt.axes(rect_scatter)
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy)

# no labels
axHistx.xaxis.set_major_formatter(nullfmt)
axHisty.yaxis.set_major_formatter(nullfmt)

# the scatter plot:
axScatter.scatter(x, y)

axScatter.set_xlim((-0.1, 0.7))
axScatter.set_ylim((-0.1, 0.5))

bins = 20
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')

axHistx.set_xlim(axScatter.get_xlim())
axHisty.set_ylim(axScatter.get_ylim())

plt.show()

enter image description here

答案 2 :(得分:0)

一个简单的想法,您可以使用np.clip()轻松完成此操作!

params_bounds = [np.clip(params_mc[i], params_bounds[i][0],params_bounds[i][1]) for i in range(len(params_mc))]