我一直在研究一种遗传算法,我试图采用我的种群中最好的模型(基于得分),并将整个种群纳入该模型。我已经成功地做到了这一点,但当我尝试分别变异每个模型时,所有模型都会变异为相同的参数。我知道这是因为我使用了一个对象,并将其克隆到一个列表中,但我不知道要更改什么,所以它不能以这种方式工作。下面我制作了一个在Python3.9中运行的可重现的例子。我知道代码不是特别小,但这是我能做的最小的代码。提前感谢,任何帮助都将不胜感激。
import torch
import torch.nn as nn
torch.manual_seed(0) #Reproducibility
population_size = 3 #Defining the size of my population
population = [nn.Linear(1,1) for _ in range(population_size)] #Initializing the population
input = torch.rand(1)# Creating dummy input
def mutate(m): #Function to mutate a model
if type(m) == nn.Linear:
m.weight = nn.Parameter(m.weight+torch.randn(m.weight.shape))
m.bias = nn.Parameter(m.bias+torch.randn(m.bias.shape))
for i in population:
print (i(input))
population = [x.apply(mutate) for x in population]
print ('\n')
for i in population:
print (i(input))
#The above works as expected
#I want to fill my entire population with that model.
#I've been filling the population with the best model by doing the following:
best_model = population[0] #Say the first model in the list was the best performing one
population = [best_model for _ in range(population_size)] #This is the line I think needs to change, I just don't know what to change it to.
#This does fill the population with my best model, but when I try to mutate it, every model is mutated to the same parameters
population = [x.apply(mutate) for x in population] #I know this is because I am using best_model while replacing the population, but I don't know how else to copy the model
for i in population:
print (i(input)) #Just to show that the population all gives the same result发布于 2021-09-28 16:09:18
您可以制作模型的深层副本。确保为import copy,然后更改
population = [best_model for _ in range(population_size)]至
population = [copy.deepcopy(best_model) for _ in range(population_size)]https://stackoverflow.com/questions/69364694
复制相似问题