1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| # 背包问题求解(动态规划也是求解这种问题的一个好方法)
max_weights = 30
weights = np.array([15, 3, 2, 5, 9, 20])
values = np.array([15, 7, 10, 5, 8, 17])
## 随机初始化一个族群 features = len(weights) # 初始样本数 init_sample_nums = np.random.randint(int(2 ** features / 3), 2 ** features) samples = np.ones((init_sample_nums, features)) # 随机给定特性(基因) for sample in range(init_sample_nums): probs = np.random.normal(0, 1, features) > 0.5 random_sample = np.zeros((features, )) random_sample[probs] = 1 samples[sample] = random_sample
# 定义函数去筛选 ## 筛选, 去除超过总重量的 def remove_the_not_fitness_sample(samples): total_weights = np.sum(samples, axis=1) not_fitness = total_weights > 30 # 保留下来的 fitness = samples[~not_fitness] return fitness
# 评分函数 ### 用于族内对比 def compare_score(samples, remove=2): # 如果直接通过最高评分判断 scores = np.zeros((len(samples, ))) for sample_index in range(len(samples)): has_feature_index = samples[sample_index] == 1 scores[sample_index] = np.sum(weights[has_feature_index]) # 排分 # 从小到大 sort_scores = np.argsort(scores) # 默认剔除最小的两个 return samples[sort_scores[2:]] ## 杂交 def crossover(samples, pairs=5, feature_prob=0.5): # 随机选取样本开始杂交 # 每一次随机选择5对开始杂交 features = len(samples[0]) copy_samples = np.copy(samples) for pair_index in range(pairs): selected = np.random.choice(range(len(samples)), 2) # 每一个位置的Gene有多大的可能性会进行杂交 cross_indexes = np.random.normal(0, 1, features) > feature_prob print(cross_indexes, selected) for cross_index in range(len(cross_indexes)): if cross_indexes[cross_index]: samples[selected[0]][cross_index] = samples[selected[1]][cross_index] copy_samples = np.append(copy_samples, samples[selected], axis=0) return copy_samples
## 变异 def mutation(samples, feature_unmutation_prob=0.8): # 每个基因(feature)的变异几率为0.2 for sample in samples: for feature in range(len(sample)): if np.random.normal(0, 1, 1) > feature_unmutation_prob: sample[feature] = 0 if sample[feature] else 1 return samples
# 执行生物论 fitness = remove_the_not_fitness_sample(samples) filter_samples = compare_score(samples) crossover_samples = crossover(filter_samples) mutation_samples = mutation(crossover_samples)
|
Comments