计算分裂lis中不同长度矩阵的均值、方差、协方差

2024-04-27 03:16:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个5个值的数组,由4个值和一个索引组成。我沿着索引对数组进行排序和拆分。这就导致了不同长度矩阵的分裂。从这里开始,我要计算平均值,方差的第四个值和协方差的前3个值为每个分裂。我目前的方法是使用for循环,我想用矩阵运算来代替它,但是我的矩阵大小不同。你知道吗

import numpy as np
A = np.random.rand(10,5) 
A[:,-1] = np.random.randint(4, size=10)
sorted_A = A[np.argsort(A[:,4])]
splits = np.split(sorted_A, np.where(np.diff(sorted_A[:,4]))[0]+1)

我的当前for循环如下所示:

result = np.zeros((len(splits), 5))
for idx, values in enumerate(splits):
    if(len(values))>0:
        result[idx, 0] = np.mean(values[:,3])
        result[idx, 1] = np.var(values[:,3])
        result[idx, 2:5] = np.cov(values[:,0:3].transpose(), ddof=0).diagonal()
    else:
        result[idx, 0] = values[:,3]

我尝试使用屏蔽数组但没有成功,因为我无法以正确的形式将矩阵加载到屏蔽数组中。也许有人知道怎么做或者有不同的建议。你知道吗


Tags: forlen排序np矩阵random数组result
1条回答
网友
1楼 · 发布于 2024-04-27 03:16:23

可以按如下方式使用np.add.reduceat

>>> idx = np.concatenate([[0], np.where(np.diff(sorted_A[:,4]))[0]+1, [A.shape[0]]])
>>> result2 = np.empty((idx.size-1, 5))
>>> result2[:, 0] = np.add.reduceat(sorted_A[:, 3], idx[:-1]) / np.diff(idx)
>>> result2[:, 1] = np.add.reduceat(sorted_A[:, 3]**2, idx[:-1]) / np.diff(idx) - result2[:, 0]**2
>>> result2[:, 2:5] = np.add.reduceat(sorted_A[:, :3]**2, idx[:-1], axis=0) / np.diff(idx)[:, None]
>>> result2[:, 2:5] -= (np.add.reduceat(sorted_A[:, :3], idx[:-1], axis=0) / np.diff(idx)[:, None])**2
>>> 
>>> np.allclose(result, result2)
True

注意协方差矩阵的对角线只是方差,这大大简化了向量化。你知道吗

相关问题 更多 >