【问题标题】:How to keep track of row index of the rows I randomly select from a matrix?如何跟踪我从矩阵中随机选择的行的行索引?
【发布时间】:2020-05-29 11:56:44
【问题描述】:

我正在尝试在 GA 中执行锦标赛选择,我需要随机选择两行。有没有办法跟踪我从矩阵 self.population 中选择的 2 个随机行的索引值并将它们存储在变量中?

目前它只输出两个随机行,但我需要跟踪选择了哪些行。

以下是我目前所拥有的,尽管理想情况下我想将从矩阵中选择的两行存储在单独的变量中。


self.population = [[0 1 1 1 0 0 1 1 0 1]
                  [1 0 1 1 0 0 0 1 1 1]
                  [0 0 0 0 0 1 1 0 0 0]
                  [1 1 0 0 1 1 1 0 1 1]
                  [0 1 0 1 1 1 1 1 1 0]
                  [0 0 0 0 1 0 1 1 1 0]]

def tournament_select(self):
    b = np.random.randint(0, self.population[0], 2) 
    return self.population[b]

【问题讨论】:

  • 只返回两个数组:return b, self.population[b]

标签: python python-3.x numpy matrix random


【解决方案1】:

这就是你要找的吗?

from random import sample
import numpy as np

population = np.array([[0, 1, 1, 1, 0, 0, 1, 1, 0, 1],
    [1, 0, 1, 1, 0, 0, 0, 1, 1, 1],
    [0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
    [1, 1, 0, 0, 1, 1, 1, 0, 1, 1],
    [0, 1, 0, 1, 1, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 1, 0, 1, 1, 1, 0]])


def tournament_select():
    row_indices = sample(range(len(population)), k=2)
    return row_indices, population[row_indices]

row_indices, candidates = tournament_select()
print(row_indices)
print(candidates)

输出:

[2, 3]
[[0 0 0 0 0 1 1 0 0 0]
 [1 1 0 0 1 1 1 0 1 1]]

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 2019-05-10
    • 2016-03-15
    • 2011-12-10
    相关资源
    最近更新 更多