Numpy __array_prepare__ error

2019-08-06 15:54发布

问题:

I'm trying to get a recipe working that I found online for doing expectation maximization (http://code.activestate.com/recipes/577735-expectation-maximization/). I run into the following error:

Traceback (most recent call last):
  File "./runem.py", line 7, in <module>
    print expectation_maximization([[1,2,3,4,5],[2,3,4,5,6],[9,8,7,4,1]], 2)
  File "/local/scratch-3/dk427/rp/em.py", line 83, in expectation_maximization
    Px[o,c] = pnorm(t[o,:], params[c]['mu'], params[c]['sigma'])
  File "/local/scratch-3/dk427/rp/em.py", line 18, in pnorm
    xmt = np.matrix(x-m).transpose()
TypeError: __array_prepare__ must return an ndarray or subclass thereof which is otherwise identical to its input

There must be some flaw in the algorithm, or I'm giving it the wrong input, but I can't find what's going wrong. I've found that the error is caused by the subtraction x-m, but x.dtype=int64 and m.dtype=float64, which I think should work.

Does anyone have any ideas?

回答1:

You seem to be passing in a list of lists rather than an array. You could do something like:

ts = np.array([[1,2,3,4,5],[2,3,4,5,6],[9,8,7,4,1]])
expectation_maximization(ts, 2)

That seems to have some problems at some point with taking a square root on my computer, but I think that might be because that data isn't good for this algorithm for some reason (but I don't know what the algorithm is trying to do, so I can't say for sure).