改写以下代码:import random import pandas as pd import numpy as np import matplotlib.pyplot as plt # 计算欧拉距离 def calcDis(dataSet, centroids, k): clalist = [] for data in dataSet: diff = np.tile(data, (k, 1)) - centroids # 相减 (np.tile(a,(2,1))就是把a先沿x轴复制1倍,即没有复制,仍然是 [0,1,2]。 # 再把结果沿y方向复制2倍得到array([[0,1,2],[0,1,2]])) squaredDiff = diff ** 2 # 平方 squaredDist = np.sum(squaredDiff, axis=1) # 和 (axis=1表示行) distance = squaredDist ** 0.5 # 开根号 clalist.append(distance) clalist = np.array(clalist) # 返回一个每个点到质点的距离len(dateSet)*k的数组 return clalist
时间: 2024-04-22 13:23:47 浏览: 60
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def calc_euclidean_distance(data_set, centroids, k):
distance_list = []
for data in data_set:
diff = np.tile(data, (k, 1)) - centroids
squared_diff = diff ** 2
squared_distance = np.sum(squared_diff, axis=1)
distance = squared_distance ** 0.5
distance_list.append(distance)
distance_array = np.array(distance_list)
# 返回每个点到质心的距离,形状为(len(data_set), k)的数组
return distance_array
阅读全文