我遇到了一个what函数,它似乎返回一个numpy数组,不管传递给它什么。在我的应用程序中,我只需要能够传递标量和列表,因此唯一的“问题”是,当我将标量传递给函数时,会返回带有一个元素的数组(当我期望得到标量时)。我应该忽略这一行为,还是黑掉函数以确保在传递标量时返回标量?
示例代码:
#! /usr/bin/env python
import scipy
import scipy.optimize
from numpy import cos
# This a some function we want to compute the inverse of
def f(x):
y = x + 2*cos(x)
return y
# Given y, this returns x such that f(x)=y
def f_inverse(y):
# This will be zero if f(x)=y
def minimize_this(x):
return y-f(x)
# A guess for the solution is required
x_guess = y
x_optimized = scipy.optimize.fsolve(minimize_this, x_guess) # THE PROBLEM COMES FROM HERE
return x_optimized
# If I call f_inverse with a list, a numpy array is returned
print f_inverse([1.0, 2.0, 3.0])
print type( f_inverse([1.0, 2.0, 3.0]) )
# If I call f_inverse with a tuple, a numpy array is returned
print f_inverse((1.0, 2.0, 3.0))
print type( f_inverse((1.0, 2.0, 3.0)) )
# If I call f_inverse with a scalar, a numpy array is returned
print f_inverse(1.0)
print type( f_inverse(1.0) )
# This is the behaviour I expected (scalar passed, scalar returned).
# Adding [0] on the return value is a hackey solution (then thing would break if a list were actually passed).
print f_inverse(1.0)[0] # <- bad solution
print type( f_inverse(1.0)[0] )在我的系统中,它的输出是:
[ 2.23872989 1.10914418 4.1187546 ]
<type 'numpy.ndarray'>
[ 2.23872989 1.10914418 4.1187546 ]
<type 'numpy.ndarray'>
[ 2.23872989]
<type 'numpy.ndarray'>
2.23872989209
<type 'numpy.float64'>我使用的是SciPy 0.10.1和MacPorts提供的Python2.7.3。
溶液
在阅读了下面的答案后,我确定了以下的解决方案。将f_inverse中的返回行替换为:
if(type(y).__module__ == np.__name__):
return x_optimized
else:
return type(y)(x_optimized)在这里,return type(y)(x_optimized)使返回类型与调用函数的类型相同。不幸的是,如果y是numpy类型,则这不起作用,因此if(type(y).__module__ == np.__name__)用于detect numpy types using the idea presented here并将它们排除在类型转换之外。
发布于 2012-09-24 14:19:34
我想wims的回答其实已经说了很多,但也许这使得差别更清楚了。
numpy返回的标量应该与array[0]一起使用(几乎?)完全兼容标准python浮点:
a = np.ones(2, dtype=float)
isinstance(a[0], float) == True # even this is true.在大多数情况下,1大小的数组与标量和列表都是兼容的,不过,例如,它是一个可变对象,而浮点数不是:
a = np.ones(1, dtype=float)
import math
math.exp(a) # works
# it is not isinstance though
isinstance(a, float) == False
# The 1-sized array works sometimes more like number:
bool(np.zeros(1)) == bool(np.asscalar(np.zeros(1)))
# While lists would be always True if they have more then one element.
bool([0]) != bool(np.zeros(1))
# And being in place might create confusion:
a = np.ones(1); c = a; c += 3
b = 1.; c = b; c += 3
a != b因此,如果用户不应该知道它,我认为第一个是好的,第二个是危险的。
还可以使用np.asscalar(result)将大小为1的数组(任意维度)转换为正确的python标量:
29: type(np.asscalar(a)) Out29: float
如果您想确保不应该知道numpy的用户没有任何惊喜,那么如果一个标量被传入,您至少必须得到0的元素。如果用户应该了解numpy,那么仅仅是文档可能也一样好。
https://stackoverflow.com/questions/12565735
复制相似问题