我正在使用Python的KNN分类器,但我有一些问题。 下面这段代码需要7.5s-9.0s才能完成,我必须运行它60.000次。我需要一些帮助来优化Python代码
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)])
的“折叠”变量是用10倍该求和包含在.csv格式的图像的输入60.000列表。每个点的第一个值是它所属的类。所有的值都是整数。 有没有办法让这条生产线更快运行?
这是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()
调用非常沉重
这里有一些链接,可以帮助:https://开头的wiki。 python.org/moin/PythonSpeed/PerformanceTips http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/benchmarks/timeit_tests.ipynb?create=1#string_operations – Totem 2014-10-27 21:39:39
请编辑您的答案以包含整个代码。还包括输入(或至少其中的一部分)。 – 2014-10-27 21:40:04
*“有助于优化Python代码”*在这里不是一个主题问题。 – jonrsharpe 2014-10-27 21:40:05