Unsized object error with numpy.random.permutation?

百般思念 提交于 2020-01-02 07:06:10

问题


I have some code right now that is getting stuck on one line:

perm = numpy.random.permutation(128)

To which it give the following error: "TypeError: len() of unsized object." I can't figure out what the issue is since 128 is just an integer. I see that this is a problem that has probably been resolved before here: http://mail.scipy.org/pipermail/numpy-discussion/2007-January/025592.html but their solution isn't helpful to me since it is about floats.

Can anyone see what's going wrong here?


回答1:


In Sage, the input is preparsed by the Sage preparser.

I'll use 12 instead of 128 so the examples fit in one line.

When you input the following:

sage: import numpy
sage: perm = numpy.random.permutation(12)

The error message you get looks like:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-38b6a5e3e889> in <module>()
----> 1 perm = numpy.random.permutation(Integer(12))

/opt/sage/local/lib/python2.7/site-packages/numpy/random/mtrand.so in mtrand.RandomState.permutation (numpy/random/mtrand/mtrand.c:21297)()

/opt/sage/local/lib/python2.7/site-packages/numpy/random/mtrand.so in mtrand.RandomState.shuffle (numpy/random/mtrand/mtrand.c:20965)()

TypeError: len() of unsized object

where you see in particular the line:

----> 1 perm = numpy.random.permutation(Integer(12))

telling you that your input

perm = numpy.random.permutation(12)

was preparsed to

perm = numpy.random.permutation(Integer(12))

However numpy is not so happy being fed a Sage Integer, it would prefer a Python int.

The simplest way to input a raw Python integer is to append r to it:

sage: perm = numpy.random.permutation(12r)

This will work for you:

sage: perm = numpy.random.permutation(12r)
sage: perm    # random
array([ 9,  0, 11,  4,  2, 10,  3,  5,  7,  6,  1,  8])

Another way is to let Sage transform the Python int to a Sage Integer but then force it to convert it back to a Python integer:

sage: perm = numpy.random.permutation(int(12))
sage: perm    # random
array([ 5,  9,  1,  7,  0,  2, 10,  6,  3,  8,  4, 11])

Another thing you could do is to turn off the Sage preparser.

sage: preparser(False)
sage: perm = numpy.random.permutation(12)
sage: perm    # random
array([ 0,  2,  7,  5,  8, 11,  1,  6,  9, 10,  3,  4])


来源:https://stackoverflow.com/questions/28426920/unsized-object-error-with-numpy-random-permutation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!