在二维匿名函数数组变量上使用 scipy.optimize.fsolve 时,I/O 形状不匹配 [英] I/O shape mismatch when using scipy.optimize.fsolve on 2-dimensional anonymous function array variable
本文介绍了在二维匿名函数数组变量上使用 scipy.optimize.fsolve 时,I/O 形状不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是源代码:
def lambdatest():F=lambda y: y-np.array([[1,2],[3,4]])y0=np.array([[3,4],[8,7]])Y=scipy.optimize.fsolve(F,y0)返回 Y
我得到的错误是:
引发 TypeError(msg)类型错误:fsolve:func"参数<lambda>"的输入和输出形状不匹配.
我环顾四周,但似乎无法理解.
解决方案
F
(fsolve
) 必须返回标量或一维数组.fsolve
不处理高维数组.
您可以做的是使用 ravel()
方法,然后将 fsolve
返回的解重新整形为二维数组:
def lambdatest():F = lambda y: y - np.array([[1,2],[3,4]]).ravel()y0 = np.array([[3,4],[8,7]])Y = scipy.optimize.fsolve(F, y0.ravel()).reshape(y0.shape)返回 Y
结果如下:
<预><代码>>>>拉姆达测试()数组([[ 1., 2.],[ 3., 4.]])Here is the source code:
def lambdatest():
F=lambda y: y-np.array([[1,2],[3,4]])
y0=np.array([[3,4],[8,7]])
Y=scipy.optimize.fsolve(F,y0)
return Y
And the error I get is:
raise TypeError(msg)
TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument '<lambda>'.
I have looked around but can't seem to make sense of it.
解决方案
F
(the func
argument of fsolve
) must return either a scalar or a one-dimensional array. fsolve
doesn't handle higher dimensional arrays.
What you can do is flatten the 2-d array to a 1-d array using the ravel()
method, and then reshape the solution returned by fsolve
into a 2-d array:
def lambdatest():
F = lambda y: y - np.array([[1,2],[3,4]]).ravel()
y0 = np.array([[3,4],[8,7]])
Y = scipy.optimize.fsolve(F, y0.ravel()).reshape(y0.shape)
return Y
Here's the result:
>>> lambdatest()
array([[ 1., 2.],
[ 3., 4.]])
这篇关于在二维匿名函数数组变量上使用 scipy.optimize.fsolve 时,I/O 形状不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文