C5.2

计算曼哈顿距离、欧氏距离、切比雪夫距离

教材页 教材5.3.2节,第144页
数据集 以鸢尾花数据集(Iris数据集)为例,实验函数调用。
任务 计算4个样例到鸢尾花iris数据集上各个样例的距离(曼哈顿距离、欧氏距离、切比雪夫距离):[4.8, 3.3, 1.5, 0.3],[5.6, 2.9, 3.5, 1.3], [6.8, 3.2, 4.6, 1.4], [6.9, 3.1, 5.2, 2.3]
Python

import numpy as np;
from scipy.spatial.distance import cityblock, euclidean, chebyshev;
from sklearn.datasets import load_iris;

# 加载鸢尾花数据集
iris = load_iris();

# 获取鸢尾花数据集的数据
X = iris.data;

# 定义要计算距离的四个样例
samples = [[4.8, 3.3, 1.5, 0.3], [5.6, 2.9, 3.5, 1.3], [6.8, 3.2, 4.6, 1.4], [6.9, 3.1, 5.2, 2.3]];

# 使用for循环计算每个样例到鸢尾花数据集上各个样例的曼哈顿距离、欧氏距离和切比雪夫距离
for sample in samples:
    manhattan_distances = [cityblock(sample, x) for x in X]; #左侧缩进4个空格
    euclidean_distances = [euclidean(sample, x) for x in X]; #左侧缩进4个空格
    chebyshev_distances = [chebyshev(sample, x) for x in X]; #左侧缩进4个空格
    print(f"Sample: {sample}"); #左侧缩进4个空格
    print(f"Manhattan distances: {manhattan_distances}"); #左侧缩进4个空格
    print(f"Euclidean distances: {euclidean_distances}"); #左侧缩进4个空格
    print(f"Chebyshev distances: {chebyshev_distances}"); #左侧缩进4个空格
    print("===" * 20); #左侧缩进4个空格

Python

自己编写Python函数来计算距离(未调用库函数)

任务:计算x1(2,3)和点x2(3,5)之间的距离。

import numpy as np

x1 = np.array([2,3])
x2 = np.array([3,5])

# 直接用公式计算欧氏距离
dist1 = np.sqrt(np.sum((x1-x2)**2))

# 使用内置范数函数计算欧氏距离
dist2 = np.linalg.norm(x1 - x2, 2)

print(f"d1={dist1},d2={dist2}\n")

# 曼哈顿距离
dist3 = np.sum(np.abs(x1-x2))
print(f"d3={dist3}\n")

# 切比雪夫距离(练习自定义函数方式计算)
def q_distance(x1,x2): return abs(x1-x2).max(); #自定义函数
print(q_distance(x1,x2)) #进行函数调用

C++ #include "orsci.h"
#include "orsci_dm.h"
using namespace orsci;
using namespace dm;
mdouble X = dmt::dataset::iris::iris_X();
mdouble A = "[4.8, 3.3, 1.5, 0.3]; [5.6, 2.9, 3.5, 1.3]; [6.8, 3.2, 4.6, 1.4]; [6.9, 3.1, 5.2, 2.3];";
for (int k = 0; k < A.rowCount(); k++)
{
rowdouble v = A.row(k);
vdouble cityblock;
vdouble euclid;
vdouble chebyshev;
for (int tt = 0; tt < X.rowCount(); tt++)
{
cityblock.push_back(X.row(tt).dist_manhattan(v));
euclid.push_back(X.row(tt).dist_euclid(v));
chebyshev.push_back(X.row(tt).dist_chebyshev(v));
}
cout << "当前向量:" << v << endl;
cout << "曼哈顿距离:" << cityblock << endl;
cout << "欧氏距离:" << euclid << endl;
cout << "切比雪夫距离:" << chebyshev << endl;
}
输出

略(各个距离,数量较大,此处略)

书籍 姜维.《数据分析与数据挖掘》、《数据分析与数据挖掘建模与工具》,电子工业出版社, 2023,2024。
软件 Python,C++(附加orsci包)。