gpt4 book ai didi

python - (A, B) 和 (C,) 之间的 Minkowski 距离

转载 作者:太空宇宙 更新时间:2023-11-04 09:37:43 24 4
gpt4 key购买 nike

我正在研究 Minkowski 距离,其定义为:

enter image description here

我使用 for 循环来计算它,如下所示,

import numpy as np
import random
A = np.random.randint(5, size=(10, 5))
B = [1, 3, 5, 2, 4]
for i in range(10):
dist = (sum((abs(A[i]-B))**5))**(1/5) # I set p=5 in this case
print("Distances: ", dist)

有什么方法可以使用 numpy 技术避免这个循环?

最佳答案

你可以使用 broadcasting :

import numpy as np
np.random.seed(42)

A = np.random.randint(5, size=(10, 5))
B = [1, 3, 5, 2, 4]


result = (np.abs(A - B)**5).sum(axis=1)**(1/5)
print(result)


for i in range(10):
dist = (sum((abs(A[i]-B))**5))**(1/5) # I set p=5 in this case
print("Distances: ", dist)

输出

[3.14564815 3.00246508 2.04767251 2.02439746 4.04953891 4.00312013
2.49663093 3.49301675 3.53370523 2.04767251]
Distances: 3.1456481457393184
Distances: 3.0024650813881837
Distances: 2.0476725110792193
Distances: 2.024397458499885
Distances: 4.049538907295691
Distances: 4.003120128600393
Distances: 2.496630931732087
Distances: 3.4930167541811468
Distances: 3.5337052340491883
Distances: 2.0476725110792193

关于python - (A, B) 和 (C,) 之间的 Minkowski 距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53066184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com