问题描述:

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-Darray 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.