简体   繁体   English

为什么我的python代码比R代码慢很多

[英]Why my python code is much slower than R code

Update 更新

Finally I found the mistake... The bug is in my full code. 最终我发现了错误...该错误在我的完整代码中。 I am a beginner in py, so... Thanks @mrdomoboto to point one error. 我是py的初学者,所以...感谢@mrdomoboto指出一个错误。 Thanks @Spacedman let me to create a reproducible example, such that I can go back to look at my full code. 谢谢@Spacedman,让我创建一个可复制的示例,以便我可以回头查看我的完整代码。

So sorry for the my noise... I will more carefully check my code before ask question. 非常抱歉,我的声音...在提出问题之前,我将更仔细地检查我的代码。 Should I delete it? 我应该删除它吗?

#

I am just doing some experiments on perceptron algorithm, and try to learn python with this practice. 我只是在感知器算法上做一些实验,并尝试通过这种做法学习python。 So I both implemented it in R and python. 所以我都在R和python中实现了它。 However I found my python code is around 10 times slower than my R code. 但是我发现我的python代码比我的R代码慢大约10倍。 Actually, I almost directly translate my R code into python. 实际上,我几乎将R代码直接转换为python。 I really want to know what is the reason. 我真的很想知道是什么原因。 Please point out the problem from my poor code. 请从我的不良代码中指出问题。

R code: R代码:

def Perceptron(X,y,ini=(0,0,0)):
    w = np.array(ini)
    N = X.shape[0]
    # add ones as the first columns of X
    X = np.hstack((np.ones(N).reshape(N,1), X))
    go_next = True
    while go_next:
        cont = 0
        for i in range(N):
            if np.sign(X[i,:].dot(w)*y[i]) == 1:
                cont = cont + 1
            else: w = w + y[i]*X[i,:]
            if cont==N: go_next=False
    return w

My py code: 我的PY代码:

 def Perceptron(X,y,ini=(0,0,0)): w = np.array(ini) N = X.shape[0] # add ones as the first columns of X X = np.hstack((np.ones(N).reshape(N,1), X)) go_next = True while go_next: cont = 0 for i in range(N): if np.sign(X[i,:].dot(w)*y[i]) == 1: cont = cont + 1 else: w = w + y[i]*X[i,:] if cont==N: go_next=False return w 

Any computations inside the inner most loops of algorithms will slow programs by an order of magnitude greater than if they were inside the outer closest lexical scope. 在算法的最内部循环中的任何计算,都会使程序的速度比在外部最接近的词法范围内的速度大一个数量级。

if cont==N: go_next=False should be moved outside of the inner most for loop ( as it is in your R program ). if cont==N: go_next=False应该移到最里面的for循环之外( 就像在R程序中一样 )。

Take a look at computational analysis . 看一下计算分析

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM