gpt4 book ai didi

python - numpy中的对角线堆叠?

转载 作者:太空狗 更新时间:2023-10-30 02:23:00 25 4
gpt4 key购买 nike

所以 numpy 有一些方便的函数可以将几个数组组合成一个,例如hstack 和 vstack。我想知道是否有类似的东西但用于对角堆叠组件阵列?

假设我有 N 个形状为 (n_i, m_i) 的数组,我想将它们组合成一个大小为 (sum_{1,N}n_i, sum_{1,N}m_i) 的数组,这样组件数组在结果数组的对角线上形成 block 。

是的,我知道如何手动解决它,例如使用 How to "embed" a small numpy array into a predefined block of a large numpy array? 中描述的方法.只是想知道是否有更简单的方法。

啊,How can I transform blocks into a blockdiagonal matrix (NumPy)提到 scipy.linalg.block_diag() 是解决方案,除了我工作站上安装的 scipy 版本太旧以至于没有它。还有其他想法吗?

最佳答案

block_diag 确实符合您的要求。因此,如果由于某种原因您无法更新 scipy,那么这里是 v0.8.0 的来源,如果您只想简单地定义它!

import numpy as np

def block_diag(*arrs):
"""Create a block diagonal matrix from the provided arrays.

Given the inputs `A`, `B` and `C`, the output will have these
arrays arranged on the diagonal::

[[A, 0, 0],
[0, B, 0],
[0, 0, C]]

If all the input arrays are square, the output is known as a
block diagonal matrix.

Parameters
----------
A, B, C, ... : array-like, up to 2D
Input arrays. A 1D array or array-like sequence with length n is
treated as a 2D array with shape (1,n).

Returns
-------
D : ndarray
Array with `A`, `B`, `C`, ... on the diagonal. `D` has the
same dtype as `A`.

References
----------
.. [1] Wikipedia, "Block matrix",
http://en.wikipedia.org/wiki/Block_diagonal_matrix

Examples
--------
>>> A = [[1, 0],
... [0, 1]]
>>> B = [[3, 4, 5],
... [6, 7, 8]]
>>> C = [[7]]
>>> print(block_diag(A, B, C))
[[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 3 4 5 0]
[0 0 6 7 8 0]
[0 0 0 0 0 7]]
>>> block_diag(1.0, [2, 3], [[4, 5], [6, 7]])
array([[ 1., 0., 0., 0., 0.],
[ 0., 2., 3., 0., 0.],
[ 0., 0., 0., 4., 5.],
[ 0., 0., 0., 6., 7.]])

"""
if arrs == ():
arrs = ([],)
arrs = [np.atleast_2d(a) for a in arrs]

bad_args = [k for k in range(len(arrs)) if arrs[k].ndim > 2]
if bad_args:
raise ValueError("arguments in the following positions have dimension "
"greater than 2: %s" % bad_args)

shapes = np.array([a.shape for a in arrs])
out = np.zeros(np.sum(shapes, axis=0), dtype=arrs[0].dtype)

r, c = 0, 0
for i, (rr, cc) in enumerate(shapes):
out[r:r + rr, c:c + cc] = arrs[i]
r += rr
c += cc
return out

关于python - numpy中的对角线堆叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7158098/

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