首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的每一个遗传算法模型都以同样的方式变异

我的每一个遗传算法模型都以同样的方式变异
EN

Stack Overflow用户
提问于 2021-09-28 15:41:20
回答 1查看 23关注 0票数 0

我一直在研究一种遗传算法,我试图采用我的种群中最好的模型(基于得分),并将整个种群纳入该模型。我已经成功地做到了这一点,但当我尝试分别变异每个模型时,所有模型都会变异为相同的参数。我知道这是因为我使用了一个对象,并将其克隆到一个列表中,但我不知道要更改什么,所以它不能以这种方式工作。下面我制作了一个在Python3.9中运行的可重现的例子。我知道代码不是特别小,但这是我能做的最小的代码。提前感谢,任何帮助都将不胜感激。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-28 16:09:18

您可以制作模型的深层副本。确保为import copy,然后更改

代码语言:javascript
复制
population = [best_model for _ in range(population_size)]

代码语言:javascript
复制
population = [copy.deepcopy(best_model) for _ in range(population_size)]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69364694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档