【问题标题】:Iterating over a function's parameters in Python (using a 2d numpy array and a list of decimals)在 Python 中迭代函数的参数(使用 2d numpy 数组和小数列表)
【发布时间】:2018-12-11 18:13:46
【问题描述】:

我定义了一个带有 2 个参数的函数:一个对称矩阵 M 和一个概率值 p。我想定义一个循环遍历我的参数的函数。循环以 0.01 的概率开始,并在到达 p 时停止。在每一步,该函数根据概率从矩阵M 中选择随机行和列并将它们删除。然后以增加的概率对新的M 执行相同的操作。我无法使用我的代码获得结果

支持小数的范围函数

def frange(start, end, step):
    tmp = start
    while tmp < end:
        yield tmp
        tmp += step

循环函数(从矩阵中随机选择行和列并删除它们)

def loop(M, p):
    for i in frange(0.01, p, 0.01):
        indices = random.sample(range(np.shape(M)[0]),
                                int(round(np.shape(M)[0] * i)))
        M = np.delete(M, indices, axis=0)  # removes rows
        M = np.delete(M, indices, axis=1)  # removes columns
        return M, indices

【问题讨论】:

    标签: python loops numpy matrix iteration


    【解决方案1】:

    像这样,您只返回Mp 作为您的第一个索引i=0.01,这是因为一旦您返回某些内容,循环就会停止。此外,由于您可以使用 python 中给出的range,所以您的第一个函数是多余的。例如,我建议您使用 List 返回您的矩阵和索引(您也可以使用 np.arrays 执行此操作)。

    def loop(M, p):
      mat_list  = []
      indices_list = []
      for i in range(0.01, p, 0.01):
          indices = random.sample(range(np.shape(M)[0]),
                                  int(round(np.shape(M)[0] * i)))
          M = np.delete(M, indices, axis=0)  # removes rows
          M = np.delete(M, indices, axis=1)  # removes columns
          mat_list.append(M)
          indices_list.append(indices)
      return mat_list, indices_list
    

    如果你还想包含概率p,那么你必须循环遍历 range(0.01, p+0.01, 0.01).

    【讨论】:

      猜你喜欢
      • 2016-07-03
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 2016-06-13
      相关资源
      最近更新 更多