【发布时间】:2020-12-11 23:24:12
【问题描述】:
我正在研究遗传算法的变异函数,但我对 numpy 还很陌生。
默认的变异方法如下所示:
whereMutate = np.random.rand(np.shape(population)[0],np.shape(population)[1])
population[np.where(whereMutate < self.mutationProb)] = 1 - population[np.where(whereMutate < self.mutationProb)]
默认的 mutationprob 设置为 1/染色体长度。种群每行包含一条不同的染色体,染色体长561条,每个位置有0或1。
我试图做的是根据该染色体的 0 和 1 的频率来设置突变概率,这样当一个 1 很少的染色体发生突变时,它就有可能将 0 切换为 1因为它是走另一条路。
目前我有这样的事情:
mProbOne = 0.5/np.count_nonzero(population, axis=1)
mProbZero = 0.5/np.count_nonzero(population == 0, axis=1)
probs = np.where(population == 0, mProbZero, mProbOne)
# Something like the above ought to give me a 2d array
# with probability of mutation for each position in the chromosome,
# separately for each chromosome
whereMutate = np.random.rand(np.shape(population)[0],np.shape(population)[1]
population[np.where(whereMutate < probs)] = 1-population[np.where(whereMutate < self.mutationProb)]
最后两行与当前存在的两行相同,用于突变概率固定的情况。 我的问题是上面的第 3 行。 mProbZero 和 mProbOne 是 1d numpy 数组。我得到了一个
ValueError: operands could not be broadcast together with shapes (2,5) (2,) (2,)
跟进:下面的代码似乎可以工作,虽然它可能比必要的多 4 行...有什么办法可以更好地做到这一点?
mProbZero = 0.5/np.count_nonzero(population == 0, axis=1)
mProbOne = 0.5/np.count_nonzero(population, axis=1)
probs = np.zeros(np.shape(population))
probs[np.where(population == 0)] = mProbZero[np.where(population == 0)[0]]
probs[np.where(population == 1)] = mProbOne[np.where(population == 1)[0]]
whereMutate = np.random.rand(np.shape(population)[0],np.shape(population)[1])
population[np.where(whereMutate < self.mutationProb)] = 1 - population[np.where(whereMutate < self.mutationProb)]
【问题讨论】:
-
你了解
numpy数组广播吗?where接受 3 个参数,它们将是标量或数组。如果是数组,它们的形状必须是兼容的——即是可广播的。你有没有看过你切断的shapes...? -
我不是很了解它。形状不匹配。它类似于 (nChromosomes, lengthChromosome) 和 (nChromosomes, ) 是否有一个很好的速记来做我想做的事情? :O
-
这样的事情似乎可行,但我认为可能有更好的方法吗? mProbZero = 0.5/np.count_nonzero(population == 0, axis=1) mProbOne = 0.5/np.count_nonzero(population, axis=1) probs = np.zeros(np.shape(population)) probs[np.where(人口 == 0)] = mProbZero[np.where(人口 == 0)[0]] 概率[np.where(人口 == 1)] = mProbOne[np.where(人口 == 1)[0]]
-
抱歉,不确定如何在评论中格式化该代码... :(
-
总是把代码放在有问题的地方,而不是放在评论里。
标签: python numpy genetic-algorithm mutation