Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vectorize inefficient python for loops with numpy #331

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions pattern/vector/svm/libsvmutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
from .libsvm import *
from .libsvm import __all__ as svm_all

import numpy as np

__all__ = ['evaluations', 'svm_load_model', 'svm_predict', 'svm_read_problem',
'svm_save_model', 'svm_train'] + svm_all

Expand Down Expand Up @@ -77,16 +79,13 @@ def evaluations(ty, pv):
if len(ty) != len(pv):
raise ValueError("len(ty) must equal to len(pv)")
total_correct = total_error = 0
sumv = sumy = sumvv = sumyy = sumvy = 0
for v, y in zip(pv, ty):
if y == v:
total_correct += 1
total_error += (v - y) * (v - y)
sumv += v
sumy += y
sumvv += v * v
sumyy += y * y
sumvy += v * y
sumv = np.sum(pv)
sumy = np.sum(ty)
sumvv = np.dot(pv,pv)
sumyy = np.dot(ty,ty)
sumvy = np.dot(pv,ty)
total_correct = np.sum([1 for v, y in zip(pv, ty) if y == v])
total_error = np.sum(np.subtract(pv, ty)**2)
l = len(ty)
ACC = 100.0 * total_correct / l
MSE = total_error / l
Expand Down