我正在用Python编写一个k最近邻分类器。但是我遇到了一个问题,就是数组操作太慢了。
def classify(k, train_data, target):
num_rows = train_data.shape[0]
num_cols = train_data.shape[1]
distances = []
candidates = [0] * 10
for i, row in enumerate(train_data):
dist = euclidean_dist(target[:num_cols - 1], row[:num_cols - 1]) #slow
distances.append((dist, row[num_cols - 1]))
distances.sort(key=lambda tup: tup[0])
distances = distances[:k]
for i, d in enumerate(distances):
candidates[d[1]] += 1
return candidates.index(max(candidates))
def euclidean_dist(x1, x2):
assert(len(x1) == len(x2))
result = 0
pdb.set_trace()
for i in range(len(x1)): #culprit, x1 and x2 are both 256 length lists
result += math.pow(x1[i] - x2[i], 2)
result = math.sqrt(result)
return result
我在上面的代码中添加了注释,显示出问题发生的位置。欢迎提出任何使其更快的建议。
np.vectorize
- Anton Protopopov