从行向量创建块矩阵的最佳方法是什么? [英] What is the best way to create a block matrix form a row vector?
本文介绍了从行向量创建块矩阵的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下numpy行矩阵。
I have the following numpy row matrix.
X = np.array([1,2,3])
我要创建一个块矩阵,如下所示:
I want to create a block matrix as follows:
1 0 0
2 1 0
3 2 1
0 3 2
0 0 3
如何使用numpy做到这一点?
How can I do this using numpy?
推荐答案
方法1:使用 np.lib.stride_tricks.as_strided
-
from numpy.lib.stride_tricks import as_strided as strided
def zeropad_arr_v1(X):
n = len(X)
z = np.zeros(len(X)-1,dtype=X.dtype)
X_ext = np.concatenate(( z, X, z))
s = X_ext.strides[0]
return strided(X_ext[n-1:], (2*n-1,n), (s,-s), writeable=False)
请注意,这将创建只读
输出。如果以后需要写,只需在末尾附加 .copy()
即可进行复制。
Note that this would create a read-only
output. If you need to write into later on, simply make a copy by appending .copy()
at the end.
方法2:使用带零的连接,然后剪切/切片-
Approach #2 : Using concatenation with zeros and then clipping/slicing -
def zeropad_arr_v2(X):
n = len(X)
X_ext = np.concatenate((X, np.zeros(n,dtype=X.dtype)))
return np.tile(X_ext, n)[:-n].reshape(-1,n,order='F')
方法#1作为基于跨步的方法应该在性能上非常有效。
Approach #1 being a strides-based method should be very efficient on performance.
示例运行-
In [559]: X = np.array([1,2,3])
In [560]: zeropad_arr_v1(X)
Out[560]:
array([[1, 0, 0],
[2, 1, 0],
[3, 2, 1],
[0, 3, 2],
[0, 0, 3]])
In [561]: zeropad_arr_v2(X)
Out[561]:
array([[1, 0, 0],
[2, 1, 0],
[3, 2, 1],
[0, 3, 2],
[0, 0, 3]])
运行时间测试
In [611]: X = np.random.randint(0,9,(1000))
# Approach #1 (read-only)
In [612]: %timeit zeropad_arr_v1(X)
100000 loops, best of 3: 8.74 µs per loop
# Approach #1 (writable)
In [613]: %timeit zeropad_arr_v1(X).copy()
1000 loops, best of 3: 1.05 ms per loop
# Approach #2
In [614]: %timeit zeropad_arr_v2(X)
1000 loops, best of 3: 705 µs per loop
# @user8153's solution
In [615]: %timeit hstack_app(X)
100 loops, best of 3: 2.26 ms per loop
这篇关于从行向量创建块矩阵的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文