0

我目前正在python中实现差分进化算法,并且在较低维度上工作时一切都很好,但是,当我开始增加搜索空间的维度时,运行算法所需的时间呈指数增长。做了一点profiling后发现大部分时间都花在了mutation函数上,具体如下,

def _mutate(self, candidate: int) -> np.ndarray:
    # r0, r1, & r2 are np.ndarrays of shape (dimension,)
    r0, r1, r2 = self._select_samples(candidate)

    # mutant is an np.ndarray of shape (dimension,)
    mutant = np.copy(self.population[candidate])

    j_rand = int(np.random.uniform() * self.dimensions)
    for j in range(self.dimensions):
        if np.random.uniform() < self.cr or j == j_rand:
            # bound the mutant to the search space
            mutant[j] = np.clip(r0[j] + self.F * (r1[j] - r2[j]),
                                self.range[0], self.range[1])

现在,对于 apopulation size100a dimension20运行算法的总时间约为 40 秒,其中约 20 秒花费在mutate.

现在,我已经对这个功能进行了优化,使其比以前的版本缩短了大约 3 秒。

def _mutate_2(self, candidate: int) -> np.ndarray:
    r0, r1, r2 = self._select_samples(candidate)
    mutant = np.copy(self.population[candidate])
    j_rand = np.random.randint(self.dimensions)
    cross_indxs = np.flatnonzero(np.random.rand(self.dimensions) < self.cr)
    cross_indxs = np.append(
        cross_indxs, [j_rand]) if j_rand not in cross_indxs else cross_indxs

    for j in cross_indxs:
        mutant[j] = np.clip(r0[j] + self.F * (r1[j] - r2[j]), self.range[0],
                            self.range[1])

    return mutant

但显然,这还不够。我想知道是否有一个技巧numpy可以删除 for 循环在r0, r1, r2, and mutant. 问题是只能cross_indxs使用索引为 in 的元素。

4

1 回答 1

0

试试这个:

mutant[cross_indxs] = (r0[cross_indxs] + self.F[cross_indxs] * (r1[cross_indxs] - r2[cross_indxs])).clip(self.range[0],self.range[1])
于 2019-11-01T12:58:57.820 回答