当前位置: 动力学知识库 > 问答 > 编程问答 >

numpy - Python Minimization involving 2D List

问题描述:

I'm trying to perform the minimization of a function f(x)

periods = range(1,11+1)

friends = range(0,7)

i = 0.05

def f(x):

sum = 0

for period in periods:

sum += x[period-1] * (1+i)**(11-period)

return -sum

optimize.fmin_cg(f, [2,2,2,2,2,2,2,2,2,2,2])

The above is for a single friend, but now we want to do it for 11 friends by adding another dimension to the list x to get x[friend][period-1] and added a new loop for friend in friends.

def g(x):

sum = 0

for period in periods:

for friend in friends:

sum += x[friend][period-1] * (1+i)**(11-period)

return -sum

optimize.fmin_cg(g, [[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2]])

However we now get the error:

IndexError: invalid index to scalar variable.

How can we solve this?

网友答案:

The docs for fmin_cg say:

x0 : ndarray

A user-supplied initial estimate of xopt, the optimal value of x. It must be a 1-D array of values.

Since the optimizer does not really care about the shape of the array, you can just flatten your x0 before passing it to fmin_cg and reshape it to the desired shape in g(), like so:

def g(x):

    sum = 0

    x = x.reshape(11, 11)

    for period in periods:
        for friend in friends:
            sum += x[friend, period-1] * (1+i)**(11-period)

    return -sum

x0 = numpy.array([[2,2,2,2,2,2,2,2,2,2,2], ...])
optimize.fmin_cg(g, x0.flatten())

Note that I used a numpy array here instead of nested lists. If you are using scipy anyway, there's no harm in learning a bit of numpy as well. It is also much easier to reshape than nested lists.

分享给朋友:
您可能感兴趣的文章:
随机阅读: