Numpy's mean and standard deviation with Numba on Python
I am trying to use Numpy's mean and standard deviation functions insinde a function and they don't seem to be compatible with Numba, although Numba documentation states them as compatible.
My code is the following:
import numpy as np
import numba
a = [1, 2, 3, 4, 5, 6]
# @numba.jit(nopython=True, parallel=True)
def nmeanstd(a, n):
b = []; c = []
for i in range(n):
b.append(np.mean(a))
c.append(np.std(a))
return b, c
mean, std = nmeanstd(a, 10)
The output when looking at mean
and std
is the expected:
mean
Out[31]: [3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5]
std
Out[32]:
[1.707825127659933,
1.707825127659933,
1.707825127659933,
1.707825127659933,
1.707825127659933,
1.707825127659933,
1.707825127659933,
1.707825127659933,
1.707825127659933,
1.707825127659933]
But I don't know why, when I uncomment the @numba.jit
function the following message appears:
TypingError: No implementation of function Function(<function mean at 0x11a0e6e50>) found for signature:
mean(reflected list(int64)<iv=None>)
There are 2 candidate implementations:
- Of which 2 did not match due to:
Overload of function 'mean': File: numba/core/typing/npydecl.py: Line 378.
With argument(s): '(reflected list(int64)<iv=None>)':
No match.
During: resolving callee type: Function(<function mean at 0x11a0e6e50>)
And the same for std
if I comment the line in which I compute the mean. What is happening? I though they would be running with numba
correctly. Do you know any way of computing the mean and the standard deviation using Numba?
Solution 1:
The error message shows that Numba does not know how to compute the mean
of a list
. Your code works fine (with @jit
) if the input list is first converted to a numpy array:
mean, std = nmeanstd(np.array(a), 10)