Python lambda function evaluation with numpys np.fromfunction
Let A1 and A2 be multidimensional arrays of the same shape, say ((d1, d2)). I want to construct an array ((d1, d1)) from it in such a way that its [i, j] th element is determined by applying the function to the tuple A1 [i], A2 [j]. I am using the np.from function in the form
f=lambda i,j: np.inner(A1[i],A2[j])
A=np.fromfunction(f, shape=(d1, d1))
(as suggested in Fastest way to initialize a numpy array with values ββgiven by a function ).
However, I get the error `` IndexError: Arrays used as indexes must be of integer (or boolean) type. '' This is weird because changing the lambda function, for example
f=lambda i,j: i*j
works great! It seems that calling another function in the lambda function leads to problems with
np.fromfunction
(np.inner is just an example, and I would like to be able to replace it with other such functions).
source to share
To debug the situation, do the f
right function and add a print statement to see the value i
and j
:
import numpy as np
np.random.seed(2015)
d1, d2 = 5, 3
A1 = np.random.random((d1,d2))
A2 = np.random.random((d1,d2))
def f(i, j):
print(i, j)
return np.inner(A1[i],A2[j])
A = np.fromfunction(f, shape=(d1, d1))
You will see (i, j)
equals:
(array([[ 0., 0., 0., 0., 0.],
[ 1., 1., 1., 1., 1.],
[ 2., 2., 2., 2., 2.],
[ 3., 3., 3., 3., 3.],
[ 4., 4., 4., 4., 4.]]), array([[ 0., 1., 2., 3., 4.],
[ 0., 1., 2., 3., 4.],
[ 0., 1., 2., 3., 4.],
[ 0., 1., 2., 3., 4.],
[ 0., 1., 2., 3., 4.]]))
Yeah. The problem is that these arrays are float-valued. As stated in the error message, indices must be of integer or boolean type.
Carrying out the docstring for np.fromfunction
shows that it has a third parameter dtype
that controls the data type of the coordinate arrays:
Parameters
dtype : data-type, optional
Data-type of the coordinate arrays passed to `function`.
By default, `dtype` is float.
So the solution is to add dtype=int
to the call np.fromfunction
:
A = np.fromfunction(f, shape=(d1, d1), dtype=int)
source to share