交换两列和2D矩阵的相同行的最快方法是什么?

时间:2017-03-22 14:59:43

标签: python numpy matrix optimization

我遇到一个问题,我需要找到列/行的最佳排列。所以当我用列j交换列i时,我必须交换第i行和第j行。分数应用于得到的矩阵(模拟退火)。

它有效,但我想知道它是否会更快。

我做什么

#!/usr/bin/env python

"""Swap rows and colums of a square integer matrix simultaneously."""

import numpy as np
import random
random.seed(0)


def swap(cm, i, j):
    """
    Swap row and column i and j in-place.

    Examples
    --------
    >>> cm = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
    >>> swap(cm, 2, 0)
    array([[8, 7, 6],
           [5, 4, 3],
           [2, 1, 0]])
    """
    # swap columns
    copy = cm[:, i].copy()
    cm[:, i] = cm[:, j]
    cm[:, j] = copy
    # swap rows
    copy = cm[i, :].copy()
    cm[i, :] = cm[j, :]
    cm[j, :] = copy
    return cm


def main(n):
    import time
    cm = np.random.randint(0, 150000, size=(n, n))
    swaps = 10**6

    t0 = time.time()
    for step in range(swaps):
        # Choose what to swap
        i = random.randint(0, n - 1)
        j = i
        while j == i:
            j = random.randint(0, n - 1)
        cm = swap(cm, i, j)
    t1 = time.time()
    print("{:0.2f} swaps / sec".format(swaps / (t1 - t0)))

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    main(369)

我尝试了什么

  • 代码原样:152642.58 swaps / sec - 158248.08 swaps / sec
  • cm[:, [i, j]] = cm[:, [j, i]]用于交换列:90562.43交换/秒 - 97625.79交换/秒

0 个答案:

没有答案