ns63sr
ns63sr

Reputation: 329

Instance of scipy.stats.rv_discrete subclass throws error on pmf() method

I want to create a subsclass of scipy.stats.rv_discrete to add some additional methods. However, when I try to access the pmf() method of the subclass, an error is raised. Please see the following example:

import numpy as np
from scipy import stats

class sub_rv_discrete(stats.rv_discrete):
  pass

xk = np.arange(2)
pk = (0.5, 0.5)

instance_subclass = sub_rv_discrete(values=(xk, pk))
instance_subclass.pmf(xk)

This results in:

Traceback (most recent call last):

  File "<ipython-input-48-129655c38e6a>", line 11, in <module>
    instance.pmf(xk)

  File "C:\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 2832, in pmf
    args, loc, _ = self._parse_args(*args, **kwds)

AttributeError: 'rv_sample' object has no attribute '_parse_args'

Despite that, if I use stats.rv_discrete directly, everything is fine:

instance_class = stats.rv_discrete(values=(xk, pk))
instance_class.pmf(xk)

---> array([ 0.5,  0.5])

Upvotes: 1

Views: 484

Answers (1)

ns63sr
ns63sr

Reputation: 329

@josef-pkt's answer on github is given below:

going through the regular subclassing creates a rv_sample class and doesn't init the correct class

the following works for me with 0.18.1 (which I have open right now)

from scipy.stats._distn_infrastructure import rv_sample

class subc_rv_discrete(rv_sample):

    def __new__(cls, *args, **kwds):
        return super(subc_rv_discrete, cls).__new__(cls)

xk = [0,1,2,3]
pk = [0.1, 0.2, 0.3, 0.4]

inst = subc_rv_discrete(values=(xk, pk))
print(inst.pmf(xk))
print(inst.__class__)

maybe this will be fixed in further scipy releases...

Upvotes: 2

Related Questions