Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何让我的代码更快地计算q2 LOO?_Python_Numpy_Scipy_Ipython_Scikit Learn - Fatal编程技术网

Python 如何让我的代码更快地计算q2 LOO?

Python 如何让我的代码更快地计算q2 LOO?,python,numpy,scipy,ipython,scikit-learn,Python,Numpy,Scipy,Ipython,Scikit Learn,我有一些代码,我已经写了计算第二季度离开一个多元线性回归,它的工作相当好的准确性方面。然而,由于我在遗传算法中使用q2LOO作为评估指标,这段代码太慢了——现在,使用我的q2LOO代码运行一次像样的GA需要几个小时。我还没有找到任何计算q2LOO的库,所以我的库使用numpy和scikit学习 import numpy as np from sklearn import cross_validation def mlrr(x_of_trainingset,y_actual): npone

我有一些代码,我已经写了计算第二季度离开一个多元线性回归,它的工作相当好的准确性方面。然而,由于我在遗传算法中使用q2LOO作为评估指标,这段代码太慢了——现在,使用我的q2LOO代码运行一次像样的GA需要几个小时。我还没有找到任何计算q2LOO的库,所以我的库使用numpy和scikit学习

import numpy as np
from sklearn import cross_validation
def mlrr(x_of_trainingset,y_actual):
    npones=np.ones(len(x_of_trainingset), float)

    A_sl=x_of_trainingset
    A=np.column_stack([A_sl,npones])

    lstsq,residuals,rank,something=np.linalg.lstsq(A, y_actual)
    return lstsq
def kfoldmlr(xi,yi,nfolds):
    x=xi.values
    y=yi.values

    kf = cross_validation.KFold(len(y), n_folds=nfolds)#indices=None, shuffle=False, random_state=None)
    y_hats=[]
    for train_index, test_index in kf:
        x_train, x_test = x[train_index], x[test_index]
        y_train=y[train_index]
        coefficients=mlrr(x_train,y_train)
        yhat=coefficients[-1]

        for index in range(x_test.size):
            slopetimesx=x_test[0][index]*coefficients[index]
            yhat=yhat+slopetimesx
        y_hats.append(float(yhat))


    stack=np.asarray(y_hats)
    return stack
def q2loo_mlr(x,y):
'''calculates q2loo of a linear regression of x and y where both x and y are 1-d'''
    yhats=kfoldmlr(x,y,len(x))
    PRESS=sum((y-yhats)**2)
    TSS=sum((y-np.mean(y))**2)
    r2cv=(TSS-PRESS)*(TSS**(-1))#1-(PRESS/TSS)
    return r2cv
测试后,这是我得到的速度:

%timeit q2loo_mlr(x, y)
10 loops, best of 3: 21.7 ms per loop

%timeit kfoldmlr(x, y, len(x))
1000 loops, best of 3: 156 µs per loop

显然,这种缓慢是由于它一次又一次地执行np.linalg.lstsq,但是还有其他选择吗?或者我还有其他方法可以加快速度吗?

因为
qloo\u mlr
kfoldmlr
的运行时是139:1,我不会认为
kfoldmlr
中对
mlr
的调用明显降低了代码的速度-
kfoldmlr
只调用一次

如果是这样的话,缓存固定索引
train\u index
的系数将是一个想法,因为系数似乎只是
train\u index
的函数,因此可以重复使用

q2loo\u mlr
中,如果您重写

TSS=sum((y-np.mean(y))**2)
作为


这会降低运行时间吗?据我所知,
np.mean(y)
是一个标量。

使用
np.sum
而不是仅仅使用
sum
通常会产生很大的不同。
y_mean = np.mean(y)
TSS=sum((y - y_mean)**2)