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. Thanks @Spacedman let me to create a reproducible example, such that I can go back to look at my full code.
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. So I both implemented it in R and python. However I found my python code is around 10 times slower than my R code. Actually, I almost directly translate my R code into python. I really want to know what is the reason. Please point out the problem from my poor code.
R code:
perceptron <- function(X,y,ini=c(0,0,0)){
w <- ini
N <- length(y)
continue <- T
while(continue){
cont <- 0
for(i in 1:N){
if(sign(sum(X[i,]*w)*y[i])==1){cont <- cont+1}
else{w <- w + y[i]*X[i,]}
}
if(cont==N){continue <- F}
}
return(w)
}
My py code:
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