相似度计算

欧式距离

使用差值的平和再求根即可以计算欧式距离,为了保证相似度的值在0-1范围内,可以使用如下公式:

相似度 = 1/(1 + 距离),当距离为0时相似度为1,距离很远时相似度为0。

# 基于欧式距离的相似度计算
def ecludSim(inA,inB):
    return 1.0/(1.0 + np.linalg.norm(inA - inB))


dataA = np.array([[2, 0, 0, 4, 4],
                  [5, 5, 5, 3, 3],
                  [2, 4, 2, 1, 2]])

print(ecludSim(dataA[:, 3], dataA[:, 4]))

皮尔逊相关系数

基于向量的相似度计算,对于(5, 5, 5)与(3, 3, 3)而言,其相似度为1,它的取值范围在-1-1之间,可以通过公式 0.5 + 0.5*corrcoef()将取值范围到0-1.

# 皮尔逊相关系数
# np.corrcoef()函数返回的类似于协方差矩阵的形式,对角元素都为1
def pearsSim(inA, inB):
    if len(inA) < 3:
        return 1.0
    return 0.5+0.5*np.corrcoef(inA, inB, rowvar=False)[0][1]

dataA = np.array([[2, 0, 0, 4, 4],
                  [5, 5, 5, 3, 3],
                  [2, 4, 2, 1, 2]])

print(pearsSim(dataA[:, 3], dataA[:, 4]))

余弦相似度

两个向量夹角的余弦值,夹角为90度时表示相似度为0,两个向量相同方向时,相似度为1,它的取值范围在-1-1之间

def cosSim(inA, inB):
    num = float(np.dot(inA, inB))
    denom = np.linalg.norm(inA)*np.linalg.norm(inB)
    return 0.5+0.5*(num/denom)


dataA = np.array([[2, 0, 0, 4, 4],
                  [5, 5, 5, 3, 3],
                  [2, 4, 2, 1, 2]])

print(cosSim(dataA[:, 0], dataA[:, 4]))