我在x_data中有一个3x2000 numpy数组,在y_data中有个1x2000 numpy阵列,我把它传递给这个函数回归,给我一条回归线。它运行良好。问题是,我正在尝试做一些回溯测试,要测试1000种情况,我必须倒退1000次,大约需要5分钟才能运行。
我试着将变量标准化,但似乎并没有让它更快。
我还试了一下fmin_powell和fmin_bfgs,它们似乎打破了它。
有什么想法吗?谢谢
def regress(x_data, y_data, fg_spread, fg_line):
theta = np.matrix(np.ones((1,x_data.shape[0]))*.11)
hyp = lambda theta, x: 1 / (1 + np.exp(-(theta*x)))
cost_hyp = lambda theta, x, y: ((np.multiply(-y,np.log10(hyp(theta,x)))) -
(np.multiply((1-y),(np.log10(1-hyp(theta, x)))))).sum()
theta = scipy.optimize.fmin(cost_hyp, theta, args=(x_data,y_data), xtol=.00001, disp=0)
return hyp(np.matrix(theta),np.matrix([1,fg_spread, fg_line]).reshape(3,1))
使用numexpr使您的hyp和cost_hyp计算更快地进行评估。fmin函数族为不同的条目多次计算这些函数。因此,这些函数的任何增益都直接报告在最小化中。
例如,您可以替换:
hyp = lambda theta, x: 1 / (1 + np.exp(-(theta*x)))
发件人:
hyp = lambda theta, x: numexpr.evaluate("1 / (1 + exp(-(theta*x)))")
Numexpr是用来处理numpy数组的。