渡されたものに関係なく、numpy 配列を返すように見える scipy 関数に遭遇しました。私のアプリケーションでは、スカラーとリストのみを渡すことができる必要があるため、唯一の「問題」は、関数にスカラーを渡すと、1 つの要素を持つ配列が返されることです (スカラーが必要な場合)。この動作を無視するか、関数をハックして、スカラーが渡されたときにスカラーが返されるようにする必要がありますか?
コード例:
#! /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'>
MacPorts が提供する SciPy 0.10.1 と Python 2.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 型の場合は機能しないため、ここで提示されたアイデアを使用して numpy 型を検出し、型変換から除外するためif(type(y).__module__ == np.__name__)
に使用されます。