I'm trying to solve for optimal values repeatedly with different random values. So the minimize function is included inside a loop and a function, then I call that function. However, it always gives me different answer.
import numpy as np
from scipy.optimize import minimize
def Ln(theta): # Every loop tries to minimize this value
error = Y - np.maximum(0, theta[0] + X.dot(theta[1:]))
error_total = np.absolute(error).sum()
return error_total
theta_true = np.array([-6,3,3,3])
Y = np.array(10)
def get_opt_x():
for i in range(10):
X = np.random.standard_normal([10,3]) # generate random values
u = X[:,0]**2*np.random.standard_normal(10)
Y_star = theta_true[0] + X.dot(theta_true[1:]) + u
Y = np.maximum(0, Y_star)
theta0 = np.ones(4)
result = minimize(Ln, theta0, method='BFGS')
print result.x
return
get_opt_x()
This is what it gives:

The correct answer is supposed to be different, since for every loop, a new set of random values are generated. If I get rid of the function, and just do the loop everything works fine:
for i in range(10):
X = np.random.standard_normal([10,3])
u = X[:,0]**2*np.random.standard_normal(10)
Y_star = theta_true[0] + X.dot(theta_true[1:]) + u
Y = np.maximum(0, Y_star)
theta0 = np.ones(4)
result = minimize(Ln, theta0, method='BFGS')
print result.x

There must be something wrong with using minimize function inside a loop and another function.