Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result -- numpy fromfunction with constant functions

Tags:

python

numpy

I was expecting np.fromfunction(lambda i: 1, (4,), dtype=int) to return array([1, 1, 1, 1]), but it returns the integer 1 instead. Can someone explain to me why numpy.fromfunction behaves that way? It seems to have something to do with the definition of the anonymous function (i.e., whether a parameter of the function is actually used).

>>> import numpy as np

>>> np.fromfunction(lambda i: i, (4,), dtype=int)
array([0, 1, 2, 3])

>>> np.fromfunction(lambda i: 1, (4,), dtype=int)
1

>>> np.fromfunction(lambda i: 1 + i*0, (4,), dtype=int)
array([1, 1, 1, 1])

EDIT: to clarify, my ultimate goal isn't to create array([1, 1, 1, 1]) using this method. Rather, I'm making a call of the form

np.fromfunction(lambda i: **an expression that doesn't depend on i**, (n,))

In other words, I'm trying to initialize a numpy array by repeatedly making a call to some function. (There's a call to np.random.random() in that function so I'm not making redundant calls.)

like image 395
Alan C Avatar asked Dec 22 '14 23:12

Alan C


1 Answers

@Warren Weckesser has explained why this is happening (the NumPy docs are a bit misleading here and nowhere make it clear that fromfunction is expecting a vector). If you want to make your lambda function work with fromfunction you can vectorize it explicitly:

In [1]: func = lambda i: 1
In [1]: vfunc = np.vectorize(func)
In [2]: np.fromfunction(vfunc, (4,), dtype=int)
Out[2]: array([1, 1, 1, 1])

But for this use case, I'd have thought

np.ones(4, dtype=int)

(perhaps times a constant) would be better.

like image 78
xnx Avatar answered Sep 22 '22 04:09

xnx