(1)实现街区距离的计算函数。(5分) (2)实现欧几里得距离的计算函数。(5分) (3)实现“上确界”距离的计算函数。(5分) (4)实现余弦相似度的计算函数。(15分) (5)实现马哈拉诺比斯(Mahalanobis)距离的计算函数,使用给定的两个向量做属性数据计算协方差,仅计算首尾两个点的距离即可。 (5分)
时间: 2024-01-17 13:03:01 浏览: 28
好的,我明白了。以下是对应的函数实现:
(1)街区距离计算函数:
```
def manhattan_distance(x, y):
return sum(abs(a - b) for a, b in zip(x, y))
```
(2)欧几里得距离计算函数:
```
import math
def euclidean_distance(x, y):
return math.sqrt(sum(pow(a - b, 2) for a, b in zip(x, y)))
```
(3)上确界距离计算函数:
```
def chebyshev_distance(x, y):
return max(abs(a - b) for a, b in zip(x, y))
```
(4)余弦相似度计算函数:
```
import math
def cosine_similarity(x, y):
numerator = sum(a * b for a, b in zip(x, y))
denominator = math.sqrt(sum(pow(a, 2) for a in x)) * math.sqrt(sum(pow(b, 2) for b in y))
return numerator / denominator
```
(5)马哈拉诺比斯距离计算函数:
```
import numpy as np
def mahalanobis_distance(x, y, covariance_matrix):
inv_covariance_matrix = np.linalg.inv(covariance_matrix)
diff = np.subtract(x, y)
distance = np.sqrt(np.dot(np.dot(diff, inv_covariance_matrix), diff.T))
return distance
```
注意,这里使用了 NumPy 库,需要先安装。同时,输入的 covariance_matrix 参数是一个协方差矩阵,可以使用 numpy.cov 函数计算得出。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)