gpt4 book ai didi

python - 从向量创建矩阵,其中每一行都是向量的移位版本

转载 作者:太空狗 更新时间:2023-10-29 21:25:33 24 4
gpt4 key购买 nike

我有一个像这样的 numpy 数组

import numpy as np

ar = np.array([1, 2, 3, 4])

我想创建一个如下所示的数组:

array([[4, 1, 2, 3],
[3, 4, 1, 2],
[2, 3, 4, 1],
[1, 2, 3, 4]])

因此,每一行对应于 ar,它被移动了行索引 + 1。

一个简单的实现看起来像这样:

ar_roll = np.tile(ar, ar.shape[0]).reshape(ar.shape[0], ar.shape[0])

for indi, ri in enumerate(ar_roll):
ar_roll[indi, :] = np.roll(ri, indi + 1)

这给了我想要的输出。

我的问题是是否有更聪明的方法来避免循环。

最佳答案

这是使用 NumPy strides 的一种方法基本上用剩余元素填充,然后 strides 帮助我们非常有效地创建转换后的版本 -

def strided_method(ar):
a = np.concatenate(( ar, ar[:-1] ))
L = len(ar)
n = a.strides[0]
return np.lib.stride_tricks.as_strided(a[L-1:], (L,L), (-n,n))

样本运行-

In [42]: ar = np.array([1, 2, 3, 4])

In [43]: strided_method(ar)
Out[43]:
array([[4, 1, 2, 3],
[3, 4, 1, 2],
[2, 3, 4, 1],
[1, 2, 3, 4]])

In [44]: ar = np.array([4,9,3,6,1,2])

In [45]: strided_method(ar)
Out[45]:
array([[2, 4, 9, 3, 6, 1],
[1, 2, 4, 9, 3, 6],
[6, 1, 2, 4, 9, 3],
[3, 6, 1, 2, 4, 9],
[9, 3, 6, 1, 2, 4],
[4, 9, 3, 6, 1, 2]])

运行时测试-

In [5]: a = np.random.randint(0,9,(1000))

# @Eric's soln
In [6]: %timeit roll_matrix(a)
100 loops, best of 3: 3.39 ms per loop

# @Warren Weckesser's soln
In [8]: %timeit circulant(a[::-1])
100 loops, best of 3: 2.03 ms per loop

# Strides method
In [18]: %timeit strided_method(a)
100000 loops, best of 3: 6.7 µs per loop

制作副本(如果您想进行更改,而不仅仅是用作只读数组)不会对 strides 方法造成太大伤害 -

In [19]: %timeit strided_method(a).copy()
1000 loops, best of 3: 381 µs per loop

关于python - 从向量创建矩阵,其中每一行都是向量的移位版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43735034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com