加权协方差矩阵(weighted covariance matrix)

 国内完全没一个有用的,这里给出了加权协方差矩阵计算函数。用的时候可以将权重先归一化。

def weighted_cov(values, weights):
    """
    Computes a weighted covariance matrix
    
    :param values: the array of values
    :param weights: array of weights for each entry of the values
    
    :returns sigma: the weighted covariance matrix
    """
    
    n = values.shape[1]
    sigma = np.empty((n, n))
    w = weights.sum() / (weights.sum()**2 - (weights**2).sum()) 
    average = np.average(values, axis=0, weights=weights)
    for j in range(n):
        for k in range(n):
            sigma[j, k] = w * np.sum(weights * ((values[:, j] - average[j]) * (values[:, k] - average[k])))
    return sigma

你可能感兴趣的:(ᕦ,机器学习,ᕤ,python,加权协方差,协方差)