Python 循环内的优化函数和另一个函数
我试图用不同的随机值反复求解最优值。最小化函数包含在一个循环和一个函数中,然后我调用这个函数。然而,它总是给我不同的答案Python 循环内的优化函数和另一个函数,python,loops,Python,Loops,我试图用不同的随机值反复求解最优值。最小化函数包含在一个循环和一个函数中,然后我调用这个函数。然而,它总是给我不同的答案 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 =
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()
这就是它所给予的:
正确答案应该是不同的,因为对于每个循环,都会生成一组新的随机值。如果我去掉函数,只做循环,一切都会很好:
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
在一个循环和另一个函数中使用最小化函数肯定有问题 变量
X
和Y
在get\u opt\u X()
中是get\u opt\u X()
的本地变量,在函数Ln
中不同于X
和Y
。get_opt_x()
的结果都是一样的,因为它使用了上次运行的循环中的值(通过去掉函数)。为了证明在运行第二个代码块之前尝试关闭会话并运行第一个代码块,您将得到一个错误,说明X
未初始化
解决方案:
将X
和Y
作为额外参数传递给minimize
例程
def Ln(theta, X, Y): # 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, (X, Y), method='BFGS')
print result.x
return
get_opt_x()
问题是您在函数
get_opt_x
中定义变量Y
,然后期望它对函数Ln
可见,而Python不允许这样做。当您删除get_opt_x
函数时,值Y
将在全局范围内可用,从而对Ln
函数可见
您需要告诉Python,Y
是get\u opt\u x
开头的一个全局变量:
def get_opt_x():
global Y