Spearman’s correlation coefficient--斯皮爾曼相關係數pytorch與numpy實現

Spearman’s correlation介紹

斯皮爾曼等級相關(Spearman’s correlation coefficient for ranked data)主要用於解決名稱數據和順序數據相關的問題。適用於兩列變量,而且具有等級變量性質具有線性關係的資料。由英國心理學家、統計學家斯皮爾曼根據積差相關的概念推導而來,一些人把斯皮爾曼等級相關看做積差相關的特殊形式。

公式如下:
在這裏插入圖片描述

Pytorch實現

矩陣運算實現,運行簡便快捷,變量名字可自行替換。輸入logits即可

def compute_rank_correlation(att, grad_att):
    """
    Function that measures Spearman’s correlation coefficient between target logits and output logits:
    att: [n, m]
    grad_att: [n, m]
    """
    def _rank_correlation_(att_map, att_gd):
        n = torch.tensor(att_map.shape[1])
        upper = 6 * torch.sum((att_gd - att_map).pow(2), dim=1)
        down = n * (n.pow(2) - 1.0)
        return (1.0 - (upper / down)).mean(dim=-1)

    att = att.sort(dim=1)[1]
    grad_att = grad_att.sort(dim=1)[1]
    correlation = _rank_correlation_(att.float(), grad_att.float())
    return correlation

Numpy實現

這裏調用函數前,請保證輸入的maps都已經轉成了rank的形式

def rank_correlation(att_map, att_gd):
	"""
	Function that measures Spearman’s correlation coefficient between target and output:
	"""
	n = att_map.shape[1]
	upper = 6 *np.sum(np.square(att_gd - att_map), axis=-1)
	down = n*(np.square(n)-1)
	return np.mean(1 - (upper/down))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章