Reputation: 880
I am trying to see an optimization progress when using scipy.optimize minimze.
I want to create a class, where i use some variables that exist outside of the actual optimization-function - x_it
is one of these and after each iteration the new x vector should be concatenated with the previous one. I do this cause i would like to evaluate this iterations with matplotlib (not in the following code) and because scipy does not allow callback function for some optimization-methods:
class iter_progress:
x_it=[]
def __init__(self):
pass
def build_iter():
import numpy as np
iter_progress.y_it=np.zeros((1,1), dtype=float)
iter_progress.x_it=np.zeros((1,2), dtype=float)
def obj(x):
import numpy as np
out=x[0]**2+x[1]**2
out=np.array([[out]])
x_copy=x.copy()[None]
#iter_progress.x_it=np.concatenate(iter_progress.x_it.copy(), x_copy)
#the above line is commented because it does not work
return out
def mine():
import numpy as np
from scipy.optimize import minimize
x0=np.array([[4,6]])
res=minimize(iter_progress.obj,x0=x0, method='SLSQP')
print(res.x)
in the console i do:
>>>from iter_progress import iter_progress
>>>iter_progress.build_iter()
>>>iter_progress.mine()
The Code works, but when i uncomment the line where i made a note i get:
iter_progress.x_it=np.concatenate(iter_progress.x_it.copy(), x_copy)
TypeError: only length-1 arrays can be converted to Python scalars
Upvotes: 1
Views: 2217
Reputation: 1273
To make @BiRico's comment more explicit: You forgot brackets around the arrays you want to concatenate. Like this np.concatenate((iter_progress.x_it.copy(), x_copy))
.
The first argument to np.concatenate
should be an iterable of arrays to be concatenated. The extra-brackets make a tuple out of the argument so the code works fine then.
Upvotes: 2