【发布时间】:2014-12-23 04:55:46
【问题描述】:
我正在使用 Python 开发 KNN 分类器,但我遇到了一些问题。 以下代码需要 7.5s-9.0s 才能完成,我必须运行 60.000 次。
for fold in folds:
for dot2 in fold:
"""
distances[x][0] = Class of the dot2
distances[x][1] = distance between dot1 and dot2
"""
distances.append([dot2[0], calc_distance(dot1[1:], dot2[1:], method)])
“folds”变量是一个包含 10 个折叠的列表,总和包含 60.000 个 .csv 格式的图像输入。每个点的第一个值是它所属的类。所有值都是整数。 有没有办法让这条线跑得更快?
这里是calc_distance函数
def calc_distancia(dot1, dot2, distance):
if distance == "manhanttan":
total = 0
#for each coord, take the absolute difference
for x in range(0, len(dot1)):
total = total + abs(dot1[x] - dot2[x])
return total
elif distance == "euclidiana":
total = 0
for x in range(0, len(dot1)):
total = total + (dot1[x] - dot2[x])**2
return math.sqrt(total)
elif distance == "supremum":
total = 0
for x in range(0, len(dot1)):
if abs(dot1[x] - dot2[x]) > total:
total = abs(dot1[x] - dot2[x])
return total
elif distance == "cosseno":
dist = 0
p1_p2_mul = 0
p1_sum = 0
p2_sum = 0
for x in range(0, len(dot1)):
p1_p2_mul = p1_p2_mul + dot1[x]*dot2[x]
p1_sum = p1_sum + dot1[x]**2
p2_sum = p2_sum + dot2[x]**2
p1_sum = math.sqrt(p1_sum)
p2_sum = math.sqrt(p2_sum)
quociente = p1_sum*p2_sum
dist = p1_p2_mul/quociente
return dist
编辑: 至少对于“manhanttan”方法,找到了一种使其更快的方法。而不是:
if distance == "manhanttan":
total = 0
#for each coord, take the absolute difference
for x in range(0, len(dot1)):
total = total + abs(dot1[x] - dot2[x])
return total
我放了
if distance == "manhanttan":
totalp1 = 0
totalp2 = 0
#for each coord, take the absolute difference
for x in range(0, len(dot1)):
totalp1 += dot1[x]
totalp2 += dot2[x]
return abs(totalp1-totalp2)
abs() 调用很重
【问题讨论】:
-
请编辑您的答案以包含整个代码。还包括输入(或至少部分输入)。
-
“优化python代码的一些帮助”不是这里的主题问题。
-
稍后我将不得不发布代码。我不确定我是否可以发布所有这些,因为这是一项学校作业。我得问问我的老师我能不能做到。他使用一个程序来验证抄袭。
-
同时,您是否考虑过(a)使用 NumPy 并重组您的程序,以便它可以在数组上按元素广播操作而不是循环,(b)在 PyPy 或其他一些 JIT 下运行基于实现而不是 CPython,或者 (c) 使用 Cython 编译内部循环?
标签: python optimization artificial-intelligence classification knn