Python程序:查找矩阵每行的冗余率
代码示例:
def row_redundancy(mat):
"""
计算矩阵每行的冗余率
Parameters:
mat: 二维矩阵,每行为一个样本
Returns:
row_r: list类型,表示每行的冗余率
"""
from scipy.spatial.distance import pdist, squareform
dis = pdist(mat)
dis_mat = squareform(dis)
row_r = []
for i in range(dis_mat.shape[0]):
row_r.append(1 - dis_mat[i, :].mean())
return row_r
在机器学习中,对于一个样本矩阵,我们需要了解每行的冗余率。简单来说,就是每行之间的相似度程度,愈相似则冗余度越高。
以上面这段Python代码为例,我们采用scipy提供的pdist函数计算矩阵每两行之间的距离,得到distance向量;然后通过squareform函数把distance向量还原成距离矩阵dis_mat;最后根据每行与其他样本的距离,计算每行的冗余度row_r,即1-行平均距离。
输出结果示例:
from numpy import array
mat = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
row_r = row_redundancy(mat)
print(row_r)
结果为:[0.5, 0.5, 0.5] 说明矩阵每一行之间的冗余率相同,即平均相似度为0.5。
结论
通过以上函数,我们可以较方便的计算出矩阵每行之间的冗余度,便于后续样本分配、样本降维等处理。