某些边界内的随机数组

问题描述 投票:1回答:3

我有一个数组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指定的上限和下限范围内?

感谢您的帮助。

python arrays python-3.x numpy random
3个回答
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


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)

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


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))]
© www.soinside.com 2019 - 2024. All rights reserved.