【问题标题】:Optimization function for the sum Google Maps distance总和谷歌地图距离的优化函数
【发布时间】:2018-05-31 14:33:31
【问题描述】:

我试图找到一个点(纬度/经度),以最小化谷歌地图到所有其他 N 点的距离之和。

我能够提取我的纬度和经度数组之间的谷歌地图距离,但我无法最小化我的函数。

代码

def minimize_g(input_g):
    gmaps1 = googlemaps.Client(key="xxx") 


def distance_f(x):
    dist = gmaps1.distance_matrix([x], np.array(input_g)[:,1:3])
    sum_ = 0
    for obs in range(len(np.array(df[:3]))):
        sum_+= dist['rows'][0]['elements'][obs]['distance']['value']   
    return sum_

 #initial guess: centroid
centroid = input_g.mean(axis=0)

optimization = minimize(distance_f, centroid, method='COBYLA')

return optimization.x

谢谢!

【问题讨论】:

    标签: python matrix maps distance minimize


    【解决方案1】:

    如果您正在地图上寻找与列表中所有坐标的距离最短的任何点,您可以尝试编写一个函数来计算从一个坐标到另一个坐标的距离。如果您准备好使用该功能,则只需计算从测试点到所有点的总距离。

    然后,从一些人为创建的坐标中,您将使用沿线的东西最小化到所有点的距离

    import numpy as np
    
    lats = [12.3, 12.4, 12.5]
    lons = [16.1, 15.1, 14.1]
    
    def total_distance_to_lats_and_lons(lat, lon):
        # some summation over distances from lat, lon to lats, lons
    
    # create two lists with 0.01 degree precision as an artificial grid of possibilities
    test_lats = np.arange(min(lats), max(lats), 0.01)
    test_lons = np.arange(min(lons), max(lons), 0.01)
    
    test_distances = []  # empty list to fill with the total_distance to each combination of test_lat, test_lon
    coordinate_index_combinations = []  # corresponding coordinates
    for test_lat in test_lats:
        for test_lon in test_lons:
            coordinate_combinations.append([test_lat, test_lon])  # add a combination of indices
            test_distances.append(total_distance_to_lats_and_lons(test_lat, test_lon))  # add a distance
    
    index_of_best_test_coordinate = np.argmin(test_distances)  # find index of the minimum value
    print('Best match is index {}'.format(index_of_best_test_coordinate))
    print('Coordinates: {}'.format(coordinate_combinations[index_of_best_test_coordinate]))
    print('Total distance: {}'.format(test_distances[index_of_best_test_coordinate]))
    

    这种蛮力方法有一些精度限制,很快就会变成一个昂贵的循环,所以你也可以迭代地应用这个方法,在每一轮之后找到最小值,这样迭代地提高精度并减少测试坐标列表中的起点和终点.经过几次迭代后,您应该有一个非常精确的估计。另一方面,这种迭代方法有可能收敛到多个局部最小值中的一个,只产生多个解中的一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多