You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于numpy.vectorize中excluded参数及函数调用次数异常的技术问询

Why does 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 calls mypolyval(p=[1,2,3], x=0) (taking the first element of x as 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 for x=0 and once for x=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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:57:43