使np.vectorize在标量输入上返回标量值 [英] make np.vectorize return scalar value on scalar input

查看:145
本文介绍了使np.vectorize在标量输入上返回标量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码返回一个数组,而不是预期的浮点值.

The following code returns an array instead of expected float value.

def f(x):
    return x+1
f = np.vectorize(f, otypes=[np.float])
>>> f(10.5)
array(11.5)

如果输入是标量而不是奇怪的数组类型,是否有一种方法可以强制它返回简单的标量值?

Is there a way to force it return simple scalar value if the input is scalar and not the weird array type?

我发现它很奇怪,因为np.cos,np.sin等所有其他ufunc都返回常规标量,因此默认情况下不会这样做

I find it weird it doesn't do it by default given that all other ufuncs like np.cos, np.sin etc do return regular scalars

修改: 这是有效的代码:

Edit: This the the code that works:

import numpy as np
import functools

def as_scalar_if_possible(func):
    @functools.wraps(func) #this is here just to preserve signature
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)[()]

    return wrapper

@as_scalar_if_possible
@np.vectorize
def f(x):
    return x + 1

print(f(11.5))#打印12.5

print(f(11.5)) # prints 12.5

推荐答案

从技术上讲,结果是标量,因为其形状为().例如,np.array(11.5)[0]不是有效的操作,将导致异常.实际上,在大多数情况下,返回的结果将充当标量.

The result is technically a scalar as its shape is (). For instance, np.array(11.5)[0] is not a valid operation and will result in an exception. Indeed, the returned results will act as a scalar in most circumstances.

例如

x = np.array(11.5)
print(x + 1) # prints 12.5
print(x < 12) # prints True, rather than [ True]
x[0] # raises IndexError

如果要返回适当的"标量值,则只需包装矢量化函数即可检查返回数组的形状.这就是numpy ufuncs在后台执行的操作.

If you want to get a "proper" scalar value back then you can just wrap the vectorised function to check the shape of the returned array. This is what numpy ufuncs do behind the scenes.

例如

import numpy as np

def as_scalar_if_possible(func):
    def wrapper(arr):
        arr = func(arr)
        return arr if arr.shape else np.asscalar(arr)
    return wrapper

@as_scalar_if_possible
@np.vectorize
def f(x):
    return x + 1

print(f(11.5)) # prints 12.5

这篇关于使np.vectorize在标量输入上返回标量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆