【机器学习】5种距离度量方法详解+Python实现([]+lambda+np.frompyfunc+向量法等多种方法实现)

本文详细介绍了机器学习中常用的五种距离度量方法:欧式距离、曼哈顿距离、夹角余弦、切比雪夫距离和汉明距离,并分别给出了它们的数学公式和Python实现示例。

介绍的五种距离度量方法是:欧氏距离(Euclidean Distance),曼哈顿距离(Manhattan Distance),夹角余弦(Angle Cosine),切比雪夫距离(Chebyshev Distance),汉明距离(Hamming Distance)。

1.欧式距离(Euclidean Distance)

1.1数学公式

Euclidean Distance,即两点之间的直线距离,数学公式如下所示。

(1)二维平面上两点a(x1,y1),b(x2,y2)之间的欧式距离公式


(2)n维空间上两点a(x1,x2……..xn),b(y1,y2……..yn)的欧式距离公式


1.2Python实现

欧氏距离的实现用了三种方法:

1)lambda+[]

2)function + np.frompyfunc

3)lambda + np.frompyfunc

lambda + np.frompyfunc是最舒服的一种实现(多个)序列之间相互操作的方法。

   # -*- coding: utf-8 -*-
"""
@author: 蔚蓝的天空tom
Aim:五种度量距离方法实现
"""
import numpy as np

def EM1(p):#数学公式法
    '''EuclideanMetric, 欧几里得距离, 也称欧氏距离'''
    y = lambda a,b : np.power(a-b,2)
    s = sum([y(a,b) for (a,b) in zip(p[0], p[1])])
    em = np.sqrt(s)
    return em
   
def e_func(a,b):
    '''求两个数的差的平方'''
    return np.power(a-b,2)
def EM2(P):#function + np.frompyfunc方法
    '''EuclideanMetric, 欧几里得距离, 也称欧氏距离'''
    func = np.frompyfunc(e_func, 2, 1)
    s = sum(func(P[0],P[1]))
    em = np.sqrt(s) 
    return em
    
def EM3(P):#lambda + np.frompyfunc方法
    e_func = lambda a,b : np.power(a-b,2)
    func = np.frompyfunc(e_func, 2, 1)
    s = sum(func(P[0],P[1]))
    em = np.sqrt(s)
    return em
    
def EM4(P):#向量法
    P = np.array(P)
    K = P[0] - P[1]
    em = np.sqrt(sum(K * K.T))#向量乘
    return em
    
if __name__=='__main__':
    #二维空间,(1,2), (3,4)
    p = [[1,2], #p1 = (1,2)
         [3,4]] #p2 = (3,4)
    print('em:', EM1(p), EM2(p),EM3(p), EM4(p))

    #4维空间,(1,2,3,4), (5,6,7,8)
    p = [[1,2,3,4], #p1 = (1,2,3,4)
         [5,6,7,8]] #p2 = (5,6,7,8)
    print('em:', EM1(p), EM2(p), EM3(p), EM4(p))

运行结果:

runfile('C:/Users/tom/5_distance.py', wdir='C:/Users/tom')
em: 2.82842712475 2.82842712475 2.82842712475 2.82842712475
em: 8.0 8.0 8.0 8.0

2.曼哈顿距离(Manhattan Distance)

2.1数学公式

ManhattanDistance,就是相同数轴坐标差的绝对值的和

(1)二维平面上两点a(x1,y1),b(x2,y2)之间的曼哈顿距离


(2)n维空间上两点a(x1,x2……..xn),b(y1,y2……..yn)的曼哈顿距离公式:


2.2Python实现

# -*- coding: utf-8 -*-
"""
@author: 蔚蓝的天空tom
Aim:用尽可能多的方法实现曼哈顿距离Manhattan Distance
"""
import numpy as np
def MD1(P):#数学公式法
    y = lambda a,b : np.abs(a-b)
    md = sum([y(a,b) for (a,b) in zip(P[0], P[1])])
    return md
    
def e_func(a,b):
    return np.abs(a-b)
def MD2(P):#function + np.frompyfunc方法
    func = np.frompyfunc(e_func, 2, 1)
    md = sum(func(P[0], P[1]))
    return md
    
def MD3(P):#lambda + np.frompyfunc方法
    e_func = lambda a,b : np.abs(a-b)
    func = np.frompyfunc(e_func, 2, 1)
    md = sum(func(P[0], P[1]))
    return md
    
def MD4(P):#
    e_func = lambda x: np.abs(x)
    func = np.frompyfunc(e_func, 1, 1)
    #md = sum(func(P[0] - P[1])) #error:list不支持-运算符
  P = np.array(P)
    md = sum(func(P[0] - P[1]))#np.ndarray向量减    return mdif __name__=='__main__':    #二维空间,(1,2), (3,4)    P = [[1,2], #p1 = (1,2)         [3,4]] #p2 = (3,4)    print('md:', MD1(P), MD2(P), MD3(P), MD4(P))    #n维空间,(1,2,3,4), (5,6,7,8)    P = [[1,2,3,4], #p1 = (1,2,3,4)         [5,6,7,8]] #p2 = (5,6,7,8)    print('md:', MD1(P), MD2(P), MD3(P), MD4(P))    

运行结果:

runfile('C:/Users/tom/Manhattan_Distance.py', wdir='C:/Users/tom')
md: 4 4 4 4
md: 16 16 16 16

3.夹角余弦

3.1数学公式

(1)二维平面上两向量a(x1,y1),b(x2,y2)之间的夹角余弦公式


也可以使用向量方法计算:


(2)n维空间上两点a(x1,x2……..xn),b(y1,y2……..yn)的夹角余弦公式    


3.2Python实现

# -*- coding: utf-8 -*-
"""
@author: 蔚蓝的天空tom
Aim:用尽可能多的方法实现夹角余弦angle cosine
"""

import numpy as np

def AC1(P):
    '''数学公式法'''
    #分子
    numerator = sum([(a*b) for (a,b) in zip(P[0], P[1])])
    #分母
    sq1 = np.sqrt(sum([np.power(e,2) for e in P[0]]))
    sq2 = np.sqrt(sum([np.power(e,2) for e in P[1]]))
    denominator = sq1 * sq2
    #夹角余弦公式
    ac = numerator * 1.0/denominator
    return ac
    
def e_func(a,b):
    '''实现a*b,如果计算a*a,可以传入a,a'''
    return a*b
def AC2(P):
    '''function + np.frompyfunc方法'''
    func = np.frompyfunc(e_func, 2, 1)
    #分子
    numerator = sum(func(P[0], P[1]))
    #分母
    denminator = np.sqrt(sum(func(P[0], P[0]))) * \
                 np.sqrt(sum(func(P[1], P[1])))
    #夹角余弦
    ac = numerator * 1.0/denminator
    return ac

def AC3(P):
    '''lambda + np.frompyfunc方法'''
    e_func = lambda a,b : a*b
    func = np.frompyfunc(e_func, 2, 1)
    numerator = sum(func(P[0], P[1]))
    denminator = np.sqrt(sum(func(P[0], P[0]))) *\
                 np.sqrt(sum(func(P[1], P[1])))
    ac = numerator * 1.0/denminator
    return ac

def AC4(P):
    '''向量法'''
    #numberator = sum(P[0]*P[1].T)#error:'list' object has no attribute 'T'
    P = np.array(P) #先转化为np.ndarray
    numberator = sum(P[0]*P[1].T)#向量乘
    denminator = np.sqrt(sum(P[0]*P[0].T)) *\
                 np.sqrt(sum(P[1]*P[1].T))
    ac = numberator * 1.0/denminator
    return ac
    
if __name__=='__main__':
    #二维空间,(1,2), (3,4)
    P = [[1,2], #p1 = (1,2)
         [3,4]] #p2 = (3,4)
    print('ac:', AC1(P), AC2(P), AC3(P), AC4(P))
    #n维空间,(1,2,3,4), (5,6,7,8)
    P = [[1,2,3,4], #p1 = (1,2,3,4)
         [5,6,7,8]] #p2 = (5,6,7,8)
    print('ac:', AC1(P), AC2(P), AC3(P), AC4(P))

运行结果:

runfile('C:/Users/tom/angle_cosine.py', wdir='C:/Users/tom')
ac: 0.9838699101 0.9838699101 0.9838699101 0.9838699101
ac: 0.968863931627 0.968863931627 0.968863931627 0.968863931627

4.切比雪夫距离(Chebyshev Distance)

4.1数学公式

(1)二维平面上两点a(x1,y1),b(x2,y2)之间的切比雪夫距离公式


(2)n维空间上两点a(x1,x2……..xn),b(y1,y2……..yn)的切比雪夫距离公式


4.2Python实现

# -*- coding: utf-8 -*-
"""
@author: 蔚蓝的天空tom
Aim:用尽可能多的方法实现切比雪夫距离(Chebyshev Distance)
"""

import numpy as np

def CD1(P):
    '''数学公式法'''
    y = [np.abs(a-b) for (a,b) in zip(P[0],P[1])]
    cd = max(y)
    return cd
    
def e_func(a,b):
    return np.abs(a-b)
def CD2(P):
    '''function + np.frompyfunc方法'''
    func = np.frompyfunc(e_func, 2, 1)
    cd = max(func(P[0], P[1]))
    return cd
    
def CD3(P):
    '''lambda + np.frompyfunc'''
    e_func = lambda a,b : np.abs(a-b)
    func = np.frompyfunc(e_func, 2, 1)
    cd = max(func(P[0], P[1]))
    return cd

def CD4(P):
    '''向量法'''
    P = np.array(P)
    cd = max(np.abs(P[0] - P[1])) #向量减和元素取绝对值
    return cd
    
if __name__=='__main__':
    #二维空间,(1,2), (3,4)
    P = [[1,2], #p1 = (1,2)
         [3,5]] #p2 = (3,5)
    print('cd:', CD1(P), CD2(P), CD3(P), CD4(P))
    #n维空间,(1,2,3,4), (5,7,9,11)
    P = [[1,2,3,4], #p1 = (1,2,3,4)
         [5,7,9,11]] #p2 = (5,7,9,11)
    print('cd:', CD1(P), CD2(P), CD3(P), CD4(P))

运行结果:

runfile('C:/Users/tom/cd.py', wdir='C:/Users/tom')
cd: 3 3 3 3
cd: 7 7 7 7

5.汉明距离(Hamming Distance)

5.1数学公式

概念:汉明距离(Hamming Distance)就是以理查德.卫斯里.汉明的名字命名的。在信息论中,两个等长字符串之间的汉明距离就是两个字符串对应位置的不同字符的个数。换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。

1001101与1011001之间的汉明距离就是2

95271314与95371234之间的汉明距离就是3

hello与Xello之间的汉明距离就是1

5.2Python实现

# -*- coding: utf-8 -*-
"""
@author: 蔚蓝的天空tom
Aim:尽量多的方法实现汉明距离(Hamming Distance)
"""

import numpy as np

def HD1(S):
    '''数学公式法'''
    diff = lambda a,b : (a != b and [1] or [0])[0]
    d = [diff(a,b) for (a,b) in zip(S[0], S[1])]
    hd = d.count(1)
    return hd
    
def e_func(a,b):
    return ((a!=b) and [1] or [0])[0]
def HD2(S):
    '''function + np.frompyfunc方法'''
    func = np.frompyfunc(e_func, 2, 1)
    y = func(list(S[0]), list(S[1]))
    hd = list(y).count(1)
    return hd
    
def HD3(S):
    '''lambda + np.frompyfunc方法'''
    e_func = lambda a,b : (a!=b and [1] or [0])[0]
    func = np.frompyfunc(e_func, 2, 1)
    y = func(list(S[0]), list(S[1]))
    hd = list(y).count(1)
    return hd

def HD4(S):
    '''向量法,先实现了数字字符串'''
    s1 = np.array(list(S[0]), dtype=int)#向量法的必要条件:str--->list--->array
    s2 = np.array(list(S[1]), dtype=int)    
    d = list(s1 - s2) #1)向量法,2)使用list的count(e)方法,所以array--->list
    hd = d.__len__() - d.count(0) #list的元素总数方法__len__()
    return hd

if __name__=='__main__':
    #两个字符串'1001101'与'1011001'
    S = ['1001101', '1011001']
    print('hd:', HD1(S), HD2(S), HD3(S), HD4(S))
    
    #两个字符串'95271314'与'95371234'
    S = ['95271314', '95371234']
    print('hd:', HD1(S), HD2(S), HD3(S), HD4(S))
    
    #'ideal'与‘dream’
    S = ['ideal', 'ideal']
    print('hd:', HD1(S), HD2(S))
    
    #‘study’与‘Student’
    S = ['study', 'Student']
    print('hd:', HD1(S))
    

运行结果

runfile('C:/Users/l13277/hd.py', wdir='C:/Users/l13277')
hd: 2 2 2 2
hd: 3 3 3 3
hd: 0 0
hd: 2

(end)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值