以下是使用 TensorFlow 实现遗传算法解决 TSP 问题的示例代码:
``` import tensorflow as tf import numpy as np
初始化城市坐标
cities = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], dtype=tf.float32)
随机初始化旅行顺序
def init_population(): return tf.random.shuffle(tf.range(tf.shape(cities)[0]))
计算路径长度
def path_length(path): indices = tf.stack([path[:-1], path[1:]], axis=-1) distances = tf.gather_nd(cities, indices) return tf.reduce_sum(tf.norm(distances, axis=-1))
遗传算法的交叉操作
def crossover(parents): # 随机选取交叉点 cross_point = tf.random.uniform([], 0, tf.shape(parents)[-1], dtype=tf.int32) # 将父代串连接在一起 parents = tf.concat(parents, axis=-1) # 将父代串按交叉点分割 children = tf.split(parents, [cross_point, tf.shape(parents)[-1]