生成一些随机高斯坐标后,我注意到TSP解算器返回可怕的解,但是它也会为相同的输入一遍又一遍地返回相同的可怕解。在
鉴于此代码:import numpy
import math
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
import matplotlib
%matplotlib inline
from matplotlib import pyplot, pylab
pylab.rcParams['figure.figsize'] = 20, 10
n_points = 200
orders = numpy.random.randn(n_points, 2)
coordinates = orders.tolist()
class Distance:
def __init__(self, coords):
self.coords = coords
def distance(self, x, y):
return math.sqrt((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2)
def __call__(self, x, y):
return self.distance(self.coords[x], self.coords[y])
distance = Distance(coordinates)
search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
search_parameters.first_solution_strategy = (
routing_enums_pb2.FirstSolutionStrategy.LOCAL_CHEAPEST_ARC)
search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.TABU_SEARCH
routing = pywrapcp.RoutingModel(len(coordinates), 1)
routing.SetArcCostEvaluatorOfAllVehicles(distance)
routing.SetDepot(0)
solver = routing.solver()
routing.CloseModel() # the documentation is a bit unclear on whether this is needed
assignment = routing.SolveWithParameters(search_parameters)
nodes = []
index = routing.Start(0)
while not routing.IsEnd(index):
nodes.append(routing.IndexToNode(index))
index = assignment.Value(routing.NextVar(index))
nodes.append(0)
for (a, b) in zip(nodes, nodes[1:]):
a, b = coordinates[a], coordinates[b]
pyplot.plot([a[0], b[0]], [a[1], b[1]], 'r' )
例如,对于10分,我得到了一个很好的解决方案:
更糟的是,一些明显的优化仍然存在(只需要交换两个点。在
对200美元来说太可怕了:
我想知道上面的代码是否真的做了一些ln,还是仅仅返回初始值,特别是因为大多数first_solution_strategy选项建议进行确定性初始化。在
为什么上面的TSP解算器对相同的数据返回一致的解,尽管禁忌搜索和模拟退火等都是随机的。为什么200分的解决方案如此糟糕?在
我在SearchParameters中使用了几个选项,特别是在local_search_operators中启用了“使用”字段。这没有效果,同样的非常次优解被返回。在