【问题标题】:subclass scipy's rv_continuous with custon function具有自定义功能的子类 scipy rv_continuous
【发布时间】:2018-11-15 14:47:36
【问题描述】:

我正在尝试使用临时分发创建 rv_continuous 的子类。 我有一个 pdf 的表达式,我想从中抽取随机数。但是,我什至无法获得 pdf 的图。我发布的代码显示,当我调用 dist.pdf 时,我正在获取 NaN,而调用 dist._pdf 时给了我正确的答案(在我设置的范围内)。

这是一个简单的例子,打印函数应该返回相同的输出,而最后一个只给出 NaN。我很确定我以错误的方式将一些参数传递给dist.pdf,但我不是 scipy 专家。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np

# the actual function used to compute the pdf
def _schechter(M, alpha, phi, Mo):
    f = phi * 10.0**(0.4 * (alpha + 1) * (Mo - M))
    out = 0.4 * np.log(10.0) * np.exp(-10.0**(0.4 * (Mo - M))) * f
    return out

from scipy import stats
class sch(stats.rv_continuous):
    def _pdf(self, x, alpha, phi, Mo):
        return _schechter(x, alpha, phi, Mo)

# to normalize the distribution, it has to be limited on the right, b cannot be
# np.inf
dist = sch(name='schecter', b=0.)


x_real = np.linspace(-100, -1, 100)
print(_schechter(x_real , -1.4, 1., -21))
print(dist._pdf(x_real, alpha=-1.4, phi=1., Mo=-21))
print(dist.pdf(x_real, -1.4, 1., -21.))

有人可以帮助我吗? 非常感谢

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    我的问题很简单:如文档所述

    如果您的 RV 的肯定参数检查不正确,那么您还需要重新定义 _argcheck 方法。

    通过重新定义 _argcheck 函数,我让它工作了。

    def _argcheck(self, *args):
        """Default check for correct values on args and keywords.
        Returns condition array of 1's where arguments are correct and
         0's where they are not.
        """
        cond = 1
        for arg in args:
            cond = np.logical_and(cond, (np.asarray(arg) > -np.inf))
        return cond
    

    【讨论】:

      【解决方案2】:

      @andrea dist.pdf 具有以下参数。请查看文档字符串以获取更多信息。

      Signature: dist.pdf(x, *args, **kwds)
      Docstring:
      Probability density function at x of the given RV.
      
      Parameters
      ----------
      x : array_like
          quantiles
      arg1, arg2, arg3,... : array_like
          The shape parameter(s) for the distribution (see docstring of the
          instance object for more information)
      loc : array_like, optional
          location parameter (default=0)
      scale : array_like, optional
          scale parameter (default=1)
      

      【讨论】:

      • 确实写到shape parameters will be inferred from the signature of the private methods, _pdf and _cdf of the instance. 所以我的实现应该没问题,但它返回NaN
      猜你喜欢
      • 1970-01-01
      • 2018-03-03
      • 2021-03-12
      • 2018-07-10
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 2014-05-16
      • 2012-04-28
      相关资源
      最近更新 更多