python - 如何从 bool 索引数组对原始数组进行逆向工程?

标签 python arrays numpy

好吧,我编写了一些用于矢量化对称矩阵的代码,它只需要唯一的元素并将它们转换为一维向量,同时还将非对角线元素乘以 root2:

def vectorize_mat(mat):
    assert mat.shape[0] == mat.shape[1], 'Matrix is not square'

    n = int(mat.shape[0])
    vec_len = 0.5*n*(n+1)
    weight_mat = (np.tri(n,k=-1)*np.sqrt(2))+np.identity(n)
    mask_mat = np.tri(n).astype(bool)
    vec_mat = (mat*weight_mat)[mask_mat]

    return vec_mat

这非常有效,现在我正在尝试弄清楚如何从向量重建原始数组。我已经得到了原始矩阵尺寸,如下所示:

v = len(vec_mat)
n = isqrt(2*v)

其中 isqrt() 是一个整数平方根:Integer square root in python

但我正在努力思考下一步该做什么。我现在可以重建权重和掩模矩阵。显然,我可以对权重矩阵进行矢量化并将向量除以它,或者将重建的矩阵除以权重矩阵以撤消该步骤,但我不知道如何进行 reshape 和其他内容(来自 bool 索引) 。也许那里有一些 super 简单的答案,但我似乎看不到它。

最佳答案

回答您的标题问题。索引 - 包括 bool 索引 - 可用于赋值。

这是一个例子。让我们首先使用蒙版提取下三角形。

>>> a = np.arange(25).reshape(5, 5)
>>> y, x = np.ogrid[:5, :5]
>>> lower = y>=x
>>> b = a[lower]

现在 b 包含下三角形。我们可以使用相同的掩模来重建下三角形并对称地填充上三角形:

>>> recon = np.empty_like(a)
>>> recon[lower] = b
>>> recon.T[lower] = b
>>> recon
array([[ 0,  5, 10, 15, 20],
       [ 5,  6, 11, 16, 21],
       [10, 11, 12, 17, 22],
       [15, 16, 17, 18, 23],
       [20, 21, 22, 23, 24]])

关于python - 如何从 bool 索引数组对原始数组进行逆向工程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53318116/

相关文章:

python - Pylons Paster shell 无法在 ipython 中运行

python - 如何使用另一个列表通过列表理解对列表进行子集化

arrays - 在 Firebase 数据库中存储数组

Java平均方法卡住了

python numpy 掩码意味着性能

python - 如何使 python 对象 json 序列化?

python - Dataframe 中多行的条件累积和

php - 使用另一个数组作为输入对数组进行排序

python-3.x - MoviePy 错误 : The system cannot find the file specified

python - 使用像 numpy 数组这样的函数