Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The behavior of numpy.fromfunction()

I was trying to create different arrays using Numpy's fromfunction(). It was working fine until I faced this issue. I tried to make an array of ones using fromfunction()(I know I can create it using ones() and full()) and here is the issue :

array = np.fromfunction(lambda i, j: 1, shape=(2, 2), dtype=float)
print(array)

Surprisingly, the output of this function is this :

1

Which is expected to be :

[[1. 1.]
 [1. 1.]]

When I change the input function by adding zero times i, It works just fine.

array = np.fromfunction(lambda i, j: i*0 + 1, shape=(2, 2), dtype=float)
print(array)

The output of this code is :

[[1. 1.]
 [1. 1.]]

My main question is how does fromfunction() actually behaves? I passed the same function with 2 different representations and the output is completely different.

like image 393
Mohsen_Fatemi Avatar asked May 09 '26 21:05

Mohsen_Fatemi


2 Answers

The callable function is passed two arrays, not repeatedly called with two numbers:

i=[ [ 0.0, 0.0 ],
    [ 1.0, 1.0 ] ]

j=[ [ 0.0, 1.0 ],
    [ 0.0, 1.0 ] ]

It returns what it is asked to provide ... just ONCE ... to be the ultimate result of np.fromfunction.

So an input of 1 returns just 1 whereas an input of i*0+1 returns

[ [ 0.0, 0.0 ],
  [ 1.0, 1.0 ] ] * 0 + 1

which is the (broadcast) array

[ [ 1.0, 1.0 ],
  [ 1.0, 1.0 ] ]
like image 145
lastchance Avatar answered May 12 '26 12:05

lastchance


This is the definition of the function

numpy.fromfunction(function, shape, *, dtype=<class 'float'>, like=None, **kwargs)

function : callable

The function is called with N parameters, where N is the rank of shape. Each parameter represents the coordinates of the array varying along a specific axis. For example, if shape were (2, 2), then the parameters would be array([[0, 0], [1, 1]]) and array([[0, 1], [0, 1]])

shape(N,) : tuple of ints

Shape of the output array, which also determines the shape of the coordinate arrays passed to function.

Returns: fromfunction : any

The result of the call to function is passed back directly. Therefore the shape of fromfunction is completely determined by function. If function returns a scalar value, the shape of fromfunction would not match the shape parameter.

emphasis is mine.

Document: https://numpy.org/doc/stable/reference/generated/numpy.fromfunction.html#numpy-fromfunction

like image 30
Talha Tayyab Avatar answered May 12 '26 11:05

Talha Tayyab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!