用 Python 中的随机点制作欧几里得距离矩阵
Making an Euclidean Distance Matrix with Random Points in Python
我编写了一段代码,可以在坐标系中的特定宽度和长度范围内生成所需数量的点。我如何计算和制表我使用欧几里得方法生成的这些点的距离矩阵?
import random
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
输出为:
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.52, 3.73), (9.69, 6.87), (8.20, 6.14), (4.18, 0.76)
Process finished with exit code 0
我怎样才能像这个例子那样创建一个带有随机点的距离矩阵:
非常感谢您的帮助。
如果要使用外部模块,scipy
矩阵计算效率很高
import random
import pandas as pd
from scipy.spatial import distance
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
#Create a matrix from these points
mat_dist = distance.cdist(sample, sample, 'euclidean')
df_mat_dist = pd.DataFrame(mat_dist)
print(df_mat_dist)
输出
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.89, 8.85), (9.00, 9.43), (9.67, 9.45), (3.96, 5.68)
0 1 2 3
0 0.000000 0.584322 0.985072 5.856736
1 0.584322 0.000000 0.669935 6.277323
2 0.985072 0.669935 0.000000 6.839240
3 5.856736 6.277323 6.839240 0.000000
我编写了一段代码,可以在坐标系中的特定宽度和长度范围内生成所需数量的点。我如何计算和制表我使用欧几里得方法生成的这些点的距离矩阵?
import random
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
输出为:
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.52, 3.73), (9.69, 6.87), (8.20, 6.14), (4.18, 0.76)
Process finished with exit code 0
我怎样才能像这个例子那样创建一个带有随机点的距离矩阵:
非常感谢您的帮助。
如果要使用外部模块,scipy
矩阵计算效率很高
import random
import pandas as pd
from scipy.spatial import distance
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
#Create a matrix from these points
mat_dist = distance.cdist(sample, sample, 'euclidean')
df_mat_dist = pd.DataFrame(mat_dist)
print(df_mat_dist)
输出
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.89, 8.85), (9.00, 9.43), (9.67, 9.45), (3.96, 5.68)
0 1 2 3
0 0.000000 0.584322 0.985072 5.856736
1 0.584322 0.000000 0.669935 6.277323
2 0.985072 0.669935 0.000000 6.839240
3 5.856736 6.277323 6.839240 0.000000