机器学习笔记--1.3数学基础

本文介绍了多种数学距离计算方法及相似度计算方法,并通过Python代码实现这些计算方法,包括曼哈顿距离、欧式距离、切比雪夫距离、夹角余弦、汉明距离和杰卡德相似系数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.范数

L1范数:各个元素绝对值之和;

L2范数:各个元素平方和的开方;

Lp范数:各个元素绝对值p次方和的1/p次方;

L∞范数:各个元素绝对值最大的那个元素。

A = (8, 1, 6)
#手工计算
modA = sqrt(sum(power(A, 2)))
print("modA:", modA)
#库函数
norma = linalg.norm(A)
print("norm(A):", normA)

2.各类距离的python实现

2.1曼哈顿距离

from numpy import *
vector1 = mat([1, 2, 3])
vector2 = mat([4, 5, 6])
print(sum(abs(vector1 - vector2)))

2.2欧式距离

from numpy import *
vector1 = mat([1, 2, 3])
vector2 = mat([4, 5, 6])
print(sqrt((vector1 - vector2) * (vector1 - vector2).T))

2.3切比雪夫距离

from numpy import *
vector1 = mat([1, 2, 3])
vector2 = mat([4, 7, 5])
print(abs(vector1 - vector2).max())

2.4夹角余弦

from numpy import *
vector1 = ([1, 2, 3])
vector2 = ([4, 7, 5])
cosV12 = dot(vector1, vector2) / (linalg.norm(vector1) * linalg.norm(vector2))
print cosV12

2.5汉明距离

from numpy import *
matV = mat([[1, 1, 0, 1, 0, 1, 0, 0, 1], [0, 1, 1, 0, 0, 0, 1, 1, 1]])
smstr = nonzero(matV[0] - matV[1])
print(shape(smstr[0])[0])

2.6杰卡德相似系数

杰卡德相似系数是衡量两个集合的相似度的一种指标。

from numpy import *
import scipy.spatial.distance as dist    #导入Scipy距离公式
matV = mat([[1, 1, 0, 1, 0, 1, 0, 0, 1], [0, 1, 1, 0, 0, 0, 1, 1, 1]])
print ("dist.jaccard:", dist.pdist(matV,'jaccard'))

        输出结果:

        dist.jaccard: [0.75]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值