from math import * import numpy as np # 计算街区距离 def i_city_dist(x, y): # -------- 请在此处完成街区距离计算函数---------------------------- # 计算欧几里得距离 def i_euclid_dist(x, y): # -------- 请在此处完成欧几里得距离计算函数---------------------------- # 计算max距离 def i_max_dist(x, y): # -------- 请在此处完成max距离计算函数---------------------------- # 计算余弦相似度 def i_vec_cos(x, y): # -------- 请在此处完成余弦相似度计算函数---------------------------- #计算Mahalanobis距离 def i_maha_dist(x, y): # -------- 请在此处完成Mahalanobis距离计算函数---------------------------- x = np.array([1,2,3,4,5,6,7,8,9,10]) y = np.array([1157,1238,1358,1467,1584,1687,1789,1852,1911,1998]) print(i_city_dist(x,y)) print(i_euclid_dist(x, y)) print(i_vec_cos(x, y)) print(i_maha_dist(x,y))
时间: 2023-08-15 19:30:34 浏览: 141
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
以下是代码实现,供参考:
```python
from math import *
import numpy as np
# 计算街区距离
def i_city_dist(x, y):
return sum([abs(x[i] - y[i]) for i in range(len(x))])
# 计算欧几里得距离
def i_euclid_dist(x, y):
return sqrt(sum([(x[i] - y[i]) ** 2 for i in range(len(x))]))
# 计算max距离
def i_max_dist(x, y):
return max([abs(x[i] - y[i]) for i in range(len(x))])
# 计算余弦相似度
def i_vec_cos(x, y):
dot_product = np.dot(x, y)
norm_x = np.linalg.norm(x)
norm_y = np.linalg.norm(y)
return dot_product / (norm_x * norm_y)
# 计算Mahalanobis距离
def i_maha_dist(x, y):
cov = np.cov([x, y])
inv_cov = np.linalg.inv(cov)
diff = x - y
return sqrt(np.dot(np.dot(diff, inv_cov), diff))
x = np.array([1,2,3,4,5,6,7,8,9,10])
y = np.array([1157,1238,1358,1467,1584,1687,1789,1852,1911,1998])
print(i_city_dist(x,y))
print(i_euclid_dist(x, y))
print(i_vec_cos(x, y))
print(i_maha_dist(x,y))
```
注意,余弦相似度和马氏距离的计算需要使用NumPy库,因此在代码中导入了NumPy库。此外,在计算马氏距离时需要计算输入数据的协方差矩阵,因此使用了NumPy库的 cov 函数。
阅读全文