|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import numpy as np
from PIL import Image
import random
import matplotlib as plt
# Step 1: 初始化种群
def init_population(pop_size, gene_size):
population = []
for i in range(pop_size):
gene = np.random.randint(256, size=(gene_size, gene_size, 3))
population.append(gene)
return population
# Step 2: 计算适应度
def fitness(target, gene):
diff = target - gene
return 1 / (1 + np.sum(np.abs(diff)))
# Step 3: 交叉
def crossover(parent1, parent2):
child1 = parent1.copy()
child2 = parent2.copy()
r1, r2 = np.random.randint(0, parent1.shape[0], 2)
c1, c2 = np.random.randint(0, parent1.shape[1], 2)
child1[r1:c1, r2:c2] = parent2[r1:c1, r2:c2]
child2[r1:c1, r2:c2] = parent1[r1:c1, r2:c2]
return child1, child2
# Step 4: 变异
def mutation(child, mutation_rate):
for i in range(child.shape[0]):
for j in range(child.shape[1]):
for k in range(child.shape[2]):
if random.random() < mutation_rate:
child[i, j, k] = np.random.randint(256)
return child
# Step 5: 选择
def selection(population, target, mutation_rate, elite_size):
pop_size = len(population)
# Step 5.1: 计算适应度
fitness_scores = [fitness(target, gene) for gene in population]
# Step 5.2: 选择精英个体
elite = []
elite_indices = np.argsort(fitness_scores)[-elite_size:]
for i in elite_indices:
elite.append(population[i])
# Step 5.3: 选择杂交个体
parents = []
for i in range(pop_size - elite_size):
parent1 = population[np.random.randint(pop_size)]
parent2 = population[np.random.randint(pop_size)]
child1, child2 = crossover(parent1, parent2)
child1 = mutation(child1, mutation_rate)
child2 = mutation(child2, mutation_rate)
parents.append(child1)
parents.append(child2)
# Step 5.4: 合并精英和杂交个体
next_population = elite + parents
return next_population
# Step 6: 主函数
def main(target_path, pop_size, gene_size, elite_size, mutation_rate, epochs):
# Step 6.1: 读取目标图像
target = np.asarray(Image.open(target_path))
# Step 6.2: 初始化种群
population = init_population(pop_size, gene_size)
for epoch in range(epochs):
# Step 6.3: 进行选择
population = selection(population, target, mutation_rate, elite_size)
# Step 6.4: 打印当前的最佳适应度
fitness_scores = [fitness(target, gene) for gene in population]
best_fitness = np.max(fitness_scores)
print("Epoch: %d, Best Fitness: %f" % (epoch, best_fitness))
# Step 6.5: 保存当前最佳个体
best_index = np.argmax(fitness_scores)
best_gene = population[best_index]
best_image = Image.fromarray(best_gene.astype(np.uint8))
best_image.save("best_image_%d.png" % epoch)
# Step 6.6: 保存最终结果
best_index = np.argmax(fitness_scores)
best_gene = population[best_index]
best_image = Image.fromarray(best_gene.astype(np.uint8))
best_image.save("final_image.png")
best_image.show()
plt.show()
target_path = input("请输入一个图片文件路径(去""):")
pop_size = input("请输入种群大小:")
gene_size = input("请输入个体宽高:")
elite_size = input("请输入保留精英个体数量,10%pop:")
mutation_rate = input("请输入变异率:")
epochs = input("请输入迭代次数(不能设定太小):")
这个是一个遗传算法用于处理图像,当我已经对一张1280*1024像素的图片设定了参数,请输入种群大小:1000,请输入个体宽高:1310720,请输入保留精英个体数量,10%pop:150,请输入变异率:0.15,请输入迭代次数(不能设定太小):400,为什么只显示进程已结束,退出代码,并没有保存图片;后来有在末尾加了plt.show(),还是没有显示或者保存图片。这是什么原因呢?是参数问题吗
本帖最后由 BrownSugar 于 2023-5-22 21:01 编辑
一个是你的代码没有调用遗传算法主函数main,其次input的结果是字符串,传入main前需要转成int、float,做好这两步后还会有个问题,gene_size的位置是二维图像尺寸,但是直接输入1310720应该是不行的,我对init_population函数进行了修改,现在输入gene_size时候输入图像尺寸,如果你的图像尺寸是1280X1024,就输入1280,1024,然后就可以运行了,至于plt,由于你的代码,仅用了一个plt.show(),所以不会显示任何plt图像,如果不打算用plt,可以直接去掉,改后的代码: import numpy as np
from PIL import Image
import random
# Step 1: 初始化种群
def init_population(pop_size, gene_size):
population = []
gene_size = [int(i) for i in gene_size.split(",")]
for i in range(pop_size):
gene = np.random.randint(256, size=(gene_size[1], gene_size[0], 3))
population.append(gene)
return population
# Step 2: 计算适应度
def fitness(target, gene):
diff = target - gene
return 1 / (1 + np.sum(np.abs(diff)))
# Step 3: 交叉
def crossover(parent1, parent2):
child1 = parent1.copy()
child2 = parent2.copy()
r1, r2 = np.random.randint(0, parent1.shape[0], 2)
c1, c2 = np.random.randint(0, parent1.shape[1], 2)
child1[r1:c1, r2:c2] = parent2[r1:c1, r2:c2]
child2[r1:c1, r2:c2] = parent1[r1:c1, r2:c2]
return child1, child2
# Step 4: 变异
def mutation(child, mutation_rate):
for i in range(child.shape[0]):
for j in range(child.shape[1]):
for k in range(child.shape[2]):
if random.random() < mutation_rate:
child[i, j, k] = np.random.randint(256)
return child
# Step 5: 选择
def selection(population, target, mutation_rate, elite_size):
pop_size = len(population)
# Step 5.1: 计算适应度
fitness_scores = [fitness(target, gene) for gene in population]
# Step 5.2: 选择精英个体
elite = []
elite_indices = np.argsort(fitness_scores)[-elite_size:]
for i in elite_indices:
elite.append(population[i])
# Step 5.3: 选择杂交个体
parents = []
for i in range(pop_size - elite_size):
parent1 = population[np.random.randint(pop_size)]
parent2 = population[np.random.randint(pop_size)]
child1, child2 = crossover(parent1, parent2)
child1 = mutation(child1, mutation_rate)
child2 = mutation(child2, mutation_rate)
parents.append(child1)
parents.append(child2)
# Step 5.4: 合并精英和杂交个体
next_population = elite + parents
return next_population
# Step 6: 主函数
def main(target_path, pop_size, gene_size, elite_size, mutation_rate, epochs):
# Step 6.1: 读取目标图像
target = np.asarray(Image.open(target_path))
# Step 6.2: 初始化种群
population = init_population(pop_size, gene_size)
for epoch in range(epochs):
# Step 6.3: 进行选择
population = selection(population, target, mutation_rate, elite_size)
# Step 6.4: 打印当前的最佳适应度
fitness_scores = [fitness(target, gene) for gene in population]
best_fitness = np.max(fitness_scores)
print("Epoch: %d, Best Fitness: %f" % (epoch, best_fitness))
# Step 6.5: 保存当前最佳个体
best_index = np.argmax(fitness_scores)
best_gene = population[best_index]
best_image = Image.fromarray(best_gene.astype(np.uint8))
best_image.save("best_image_%d.png" % epoch)
# Step 6.6: 保存最终结果
best_index = np.argmax(fitness_scores)
best_gene = population[best_index]
best_image = Image.fromarray(best_gene.astype(np.uint8))
best_image.save("final_image.png")
best_image.show()
target_path = input("请输入一个图片文件路径(去""):")
pop_size = int(input("请输入种群大小:"))
gene_size = input("请输入个体宽高:")
elite_size = int(input("请输入保留精英个体数量,10%pop:"))
mutation_rate = float(input("请输入变异率:"))
epochs = int(input("请输入迭代次数(不能设定太小):"))
main(target_path,pop_size,gene_size,elite_size,mutation_rate,epochs)
你的代码在我的电脑运算有点慢,基本跑不动,所以我没用太大的图像和参数
以下是我的输入:
请输入一个图片文件路径(去):china.jpg
请输入种群大小:100
请输入个体宽高:128,102
请输入保留精英个体数量,10%pop:150
请输入变异率:0.15
请输入迭代次数(不能设定太小):1
|
|