我试图找到一组n个点的几何中位数。为此,我必须最小化sqrt((x-xn)^ 2 +(y-yn)^ 2)的总和。
为此,我决定尝试一种Gradient Descents方法。该函数的梯度只是x的(x-xn)/ sqrt((x-xn)^ 2 +(y-yn)^ 2)和y的相似值之和。但是,无论步长有多小,或者迭代次数多少,我的代码似乎都会覆盖目标。
以下是有问题的代码段
def geoMean(points, gamma, iters):
#Take the initial guess to be the centroid
guess = centerOfMass(points)
for rep in range(0, iters):
gradient = [0, 0]
for point in points:
#Sum up the partials for every point
gradient[0] += (guess[0]-point[0])/(math.sqrt((guess[0]-point[0])**2+(guess[1]-point[1])**2))
gradient[1] += (guess[1]-point[1])/(math.sqrt((guess[0]-point[0])**2+(guess[1]-point[1])**2))
#Refine the guess
guess = (guess[0]-gamma*gradient[0], guess[1]-gamma*gradient[1])
return guess
重要提示:这些点可能在任何地方,它们并非严格地位于第一象限。