如何在numpy范围内获得正态分布? [英] How to get a normal distribution within a range in numpy?

查看:71
本文介绍了如何在numpy范围内获得正态分布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在机器学习任务中.我们应该得到一组有界的随机 w.r.t 正态分布.我们可以使用 np.random.normal() 获得正态分布数,但它不提供任何绑定参数.我想知道怎么做?

解决方案

truncnorm参数化很复杂,所以这里有一个函数可以将参数化转化为更多的东西直观:

from scipy.stats import truncnormdef get_truncated_normal(mean=0, sd=1, low=0, upp=10):返回 truncnorm((low - mean)/sd, (upp - mean)/sd, loc=mean, scale=sd)

<小时><小时>

如何使用?

  1. 使用以下参数实例化生成器:mean标准差截断范围:

    <预><代码>>>>X = get_truncated_normal(mean=8, sd=2, low=1, upp=10)

  2. 然后,您可以使用 X 生成一个值:

    <预><代码>>>>X.rvs()6.0491227353928894

  3. 或者,一个包含 N 个生成值的 numpy 数组:

    <预><代码>>>>X.rvs(10)数组([ 7.70231607, 6.7005871, 7.15203887, 6.06768994, 7.25153472,5.41384242, 7.75200702, 5.5725888, 7.38512757, 7.47567455])

<小时>

视觉示例

这是三个不同截断正态分布的图:

X1 = get_truncated_normal(mean=2, sd=1, low=1, upp=10)X2 = get_truncated_normal(mean=5.5, sd=1, low=1, upp=10)X3 = get_truncated_normal(mean=8, sd=1, low=1, upp=10)导入 matplotlib.pyplot 作为 plt图, ax = plt.subplots(3, sharex=True)ax[0].hist(X1.rvs(10000), normed=True)ax[1].hist(X2.rvs(10000), normed=True)ax[2].hist(X3.rvs(10000), normed=True)plt.show()

In machine learning task. We should get a group of random w.r.t normal distribution with bound. We can get a normal distribution number with np.random.normal() but it does't offer any bound parameter. I want to know how to do that?

解决方案

The parametrization of truncnorm is complicated, so here is a function that translates the parametrization to something more intuitive:

from scipy.stats import truncnorm

def get_truncated_normal(mean=0, sd=1, low=0, upp=10):
    return truncnorm(
        (low - mean) / sd, (upp - mean) / sd, loc=mean, scale=sd)



How to use it?

  1. Instance the generator with the parameters: mean, standard deviation, and truncation range:

    >>> X = get_truncated_normal(mean=8, sd=2, low=1, upp=10)
    

  2. Then, you can use X to generate a value:

    >>> X.rvs()
    6.0491227353928894
    

  3. Or, a numpy array with N generated values:

    >>> X.rvs(10)
    array([ 7.70231607,  6.7005871 ,  7.15203887,  6.06768994,  7.25153472,
            5.41384242,  7.75200702,  5.5725888 ,  7.38512757,  7.47567455])
    


A Visual Example

Here is the plot of three different truncated normal distributions:

X1 = get_truncated_normal(mean=2, sd=1, low=1, upp=10)
X2 = get_truncated_normal(mean=5.5, sd=1, low=1, upp=10)
X3 = get_truncated_normal(mean=8, sd=1, low=1, upp=10)

import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, sharex=True)
ax[0].hist(X1.rvs(10000), normed=True)
ax[1].hist(X2.rvs(10000), normed=True)
ax[2].hist(X3.rvs(10000), normed=True)
plt.show()

这篇关于如何在numpy范围内获得正态分布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆