切比雪夫距離(Chebyshev Distance)是向量空間中的一種度量,兩個點之間的距離定義為點坐標數值差的最大值。以(x1,y1)和(x2,y2)二點為例,切比雪夫距離為
切比雪夫距離的定義為
依以上的度量,以任一點為準,和此點切比雪夫距離為r的點會形成一個正方形,其邊長為2r,且各邊都和坐標軸平行。
切比雪夫距離實現分析
在javaml庫中,切比雪夫距離實現類關係圖如下所示
ChebychevDistance類的measure()方法實現了切比雪夫距離的算法,代碼片段如下
public double measure(Instance x, Instance y) {
// 1) 檢查x和y是否屬於相同的維度範疇,如x是二維,而y是三維,則不能測量
if (x.noAttributes() != y.noAttributes())
throw new RuntimeException("Both instances should contain the same number of values.");
// 2) 計算x和y的切比雪夫距離。
double totalMax = 0.0;
for (int i = 0; i < x.noAttributes(); i++) {
totalMax = Math.max(totalMax, Math.abs(y.value(i) - x.value(i)));
}
return totalMax;
}
如在二維坐標系統點x(1,2),y(-1,0),切比雪夫距離為max(|-1-1|,|0-2|) = 2。示例代碼如下
public static void main(String[] args) {
double[] x_point = {1,2};
double[] y_point = {-1,0};
DenseInstance x = new DenseInstance(x_point);
DenseInstance y = new DenseInstance(y_point);
DistanceMeasure dm = new ChebychevDistance();
double d_chess = dm.measure(x, y);
// out: d_checss => 2.0
System.out.println("d_checss => "+d_chess);
}
在推薦系統中,我們可以使用切比雪夫距離推測兩個用戶對指定商品的喜好程度,精準地向用戶推薦符合其喜好的商品,從而增加商品訂單的變現率。