关于numpy.vectorize中excluded参数及函数调用次数异常的技术问询
numpy.vectorize call my function extra times when using excluded? Great question! Your initial intuition is totally correct—you should only see two calls, one for each element in x—so that extra call to mypolyval with x=0 is definitely confusing. Let's break down what's happening:
The hidden type-detection call in numpy.vectorize
numpy.vectorize is mostly syntactic sugar, not a true vectorization tool (it doesn't speed up your code like native numpy operations). A key part of its internal logic is that it needs to figure out what data type and shape the output array should have. To do this, it automatically calls your function once with sample inputs before processing all elements in your input arrays.
In your case:
- When you run
vpolyval(p=[1,2,3], x=[0,1]), numpy first callsmypolyval(p=[1,2,3], x=0)(taking the first element ofxas a sample) to check if the return value is an integer, float, etc. - After determining the output type, it then runs the "real" calls for each element in
x: once forx=0and once forx=1. - That's why you see three total calls instead of two.
How to fix the extra call
You can eliminate this extra call by explicitly telling numpy.vectorize what the output type should be using the otypes parameter. Here's your modified code:
import numpy as np def mypolyval(p, x): print('Called mypolyval: ',(p,x)) _p = list(p) res = _p.pop(0) while _p: res = res*x + _p.pop(0) return res # Add otypes to specify output type (int in this case) vpolyval = np.vectorize(mypolyval, excluded=['p'], otypes=[int]) res2 = vpolyval(p=[1, 2, 3], x=[0, 1]) print(res2)
Running this will give you the expected output with only two calls:
Called mypolyval: ([1, 2, 3], 0) Called mypolyval: ([1, 2, 3], 1) [3 6]
A quick note on numpy.vectorize
Keep in mind that since it's just a wrapper, vectorize doesn't offer any performance benefits over writing a loop yourself. It's mainly useful for making scalar functions feel like numpy-style functions. If your function has side effects (like print statements, or modifying external state), this hidden type-detection call can lead to unexpected behavior—so specifying otypes is a good practice in those cases.
内容的提问来源于stack exchange,提问作者Rnj

