问题描述
我对 scipy 非常业余.我正在尝试在多维变量系统上使用 scipy 的 fmin 函数.为简单起见,我使用列表列表.我的数据是 12 维的,当我输入 np.shape(DATA)
时它返回 (3,2,2)
,我什至不确定 scipy 是否可以处理那么多维度,如果不是没有问题我可以减少它们,关键是 optimize.fmin()
函数不接受基于列表的数组作为 x0
初始参数,所以我需要帮助将 x0
数组重写为 numpy 兼容的数组或将整个 DATA 数组重写为 12 维矩阵或类似的东西.
I am very amateur when it comes to scipy. I am trying to use scipy's fmin function on a multidimensional variable system. For the sake of simplicity I am using list of list of list's. My data is 12 dimensional, when I enter np.shape(DATA)
it returns (3,2,2)
, I am not even sure if scipy can handle that many dimensions, if not no problem I can reduce them, the point is that the optimize.fmin()
function doesn't accept list based arrays as x0
initial parameters, so I need help either rewriting the x0
array into numpy compatible one or the entire DATA array into a 12 dimensional matrix or something like that.
这里有一个更简单的例子来说明这个问题:
Here is a simpler example illustrating the issue:
from scipy import optimize
import numpy as np
def f(x): return(x[0][0]*1.5-x[0][1]*2.0+x[1][0]*2.5-x[1][1]*3.0)
result = optimize.fmin(f,[[0.1,0.1],[0.1,0.1]])
print(result)
它会给出一个错误,说 invalid index to scalar variable
这可能是由于不理解列表结构的 [[],[]]
列表,所以它可能只理解 numpy 数组格式.
It will give an error saying invalid index to scalar variable
which probably comes from not understanding the [[],[]]
list of list structure, so it probably only understands numpy array formats.
那么如何重写它以使其工作,以及我的(3,2,2)形状的列表列表!?
So how to rewrite this to make it work, and also for my (3,2,2) shaped list of list as well!?
推荐答案
scipy.optimize.fmin
需要函数参数的初始猜测是一维数组,其中包含适合功能来优化.在您的情况下,如果您只需要输出与输入参数的形状相同,也许您可以使用 flatten
和 reshape
.基于您的插图代码的示例:
scipy.optimize.fmin
needs the initial guess for the function parameters to be a 1D array with a number of elements that suits the function to optimize. In your case, maybe you can use flatten
and reshape
if you just need the output to be in the same shape as your input parameters. An example based on your illustration code:
from scipy import optimize
import numpy as np
def f(x):
return x[0]*1.5-x[1]*2.0+x[2]*2.5-x[3]*3.0
guess = np.array([[0.1, 0.1],
[0.1, 0.1]]) # guess.shape is (2,2)
out = optimize.fmin(f, guess.flatten()) # flatten upon input
# out.shape is (4,)
# reshape output according to guess
out = out.reshape(guess.shape) # out.shape is (2,2) again
或 out = optimize.fmin(f, guess.flatten()).reshape(guess.shape)
在一行中.请注意,这也适用于您建议的 3 维数组:
or out = optimize.fmin(f, guess.flatten()).reshape(guess.shape)
in one line. Note that this also works for a 3-dimensional array as you propose:
guess = np.arange(12).reshape(3,2,2)
# array([[[ 0, 1],
# [ 2, 3]],
# [[ 4, 5],
# [ 6, 7]],
# [[ 8, 9],
# [10, 11]]])
guess = guess.flatten()
# array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
guess = guess.reshape(3,2,2)
# array([[[ 0, 1],
# [ 2, 3]],
# [[ 4, 5],
# [ 6, 7]],
# [[ 8, 9],
# [10, 11]]])
这篇关于如何组织列表列表以与 scipy.optimize fmin init 数组兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!