1

This is an excerpt from PyBrain's website. I get most of what is going on, but one line has me completely stumped. I've never seen anything like this in python code before. Here is the whole loop, for context:

    for c in [0, 1, 2]:
        #have no friggin idea how this next line works
        here, _ = where(tstdata['class']==c)
        plot(tstdata['input'][here, 0], tstdata['input'][here, 1], 'o')

the weird "where" qualifier is from NumPy, and I get what that's doing. I've never seen "here" used that way though. Can someone explain exactly what this is doing?

4

2 回答 2

6

There is nothing magic, where is a simple function, defined somewhere else, which returns a tuple of two elements, and assign action auto unpacks them to here variable, and _ variable. If instead of function where we try with simple tuple:

>>> here, _ = ("a", "b")
>>> here
'a'
>>> _
'b'
于 2013-08-30T14:10:12.793 回答
1

pybrain is using the result to slice a multidimensional array.

>>> a
array([[3, 1, 0, 2],
       [1, 2, 1, 2],
       [1, 3, 3, 0],
       [0, 1, 0, 0]])

>>> b
array([3, 3, 1, 2])

>>> np.where(b==3)
(array([0, 1]),)

Using this naively will either return a higher dimensional array or do wonky things:

>>> a[np.where(b==3),0]
array([[3, 1]])

You can either unpack the tuple or do below to return the expected result:

>>> a[np.where(b==3)[0],0]
array([3, 1])

The reason this is dangerous:

>>> here, _ = np.where(b==3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

To change the above:

here= where(tstdata['class']==c)
plot(tstdata['input'][here[0], 0], tstdata['input'][here[0], 1], 'o')
于 2013-08-30T14:12:58.973 回答