import numpy as np # step1: randomly generate the data from sko.demo_func import function_for_TSP num_points, points_coordinate, distance_matrix, cal_total_distance = function_for_TSP( num_points=15) # %%step2: DO GA with UDF from sko.GA import GA_TSP from sko.operators import ranking, selection, crossover, mutation ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=100, prob_mut=1) ga_tsp.register('selection', selection.selection_tournament, tourn_size=3). \ register('mutation', mutation.mutation_reverse) best_points, best_distance = ga_tsp.run() print('best routine:', best_points, 'best_distance:', best_distance) # %% # step3: plot import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') plt.show()
num_points, = routine.shape return sum([ distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points) ]) from sko.GA import GA_TSP # 3 * size_pop * max_iter ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=100, max_iter=2400, prob_mut=0.07) ga_tsp.register(operator_name='crossover', operator=operators.crossover_ox) best_points, best_distance = ga_tsp.run() X = data_cities[best_points, 1] Y = data_cities[best_points, 2] plt.figure(figsize=(12, 8)) # plt.title('TSP Graph') plt.title('GA: ' + str(best_distance)) plt.xlabel('X') plt.ylabel('Y') plt.scatter(X, Y, s=140) for ind in range(num_points): plt.plot((X[ind], X[(ind + 1) % num_points]), (Y[ind], Y[(ind + 1) % num_points]),
import numpy as np # step1: randomly generate the data from sko.demo_func import function_for_TSP num_points, points_coordinate, distance_matrix, cal_total_distance = function_for_TSP( num_points=15) # step2: DO GA with UDF from sko.GA import GA_TSP from sko.GA import selection_tournament, mutation_TSP_1 ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=500, max_iter=800, Pm=0.2) ga_tsp.register('selection', selection_tournament, tourn_size=3). \ register('mutation', mutation_TSP_1) best_points, best_distance = ga_tsp.fit() print('best routine:', best_points, 'best_distance:', best_distance) # %% # step3: plot import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') plt.show()