Python_寻找并绘制距离某一点最近的k个点

def Find_Recent(x, y, x_, y_, k):
    """
    找到点集中距离目标点(x, y)最近的k个点
    :param x: 点集的x坐标
    :param y: 点集的y坐标
    :param x_: 目标点的x坐标
    :param y_: 目标点的y坐标
    :param k: 距离目标点最近的k个值
    :return: k个与目标点最近的点的集合
    """
    list_stack_temp = []  # 建立一个空的栈
    for i in range(len(x)):
        list_temp = []
        if x[i] != x_:
            length = math.sqrt(pow(x[i] - x_, 2) + pow(y[i] - y_, 2))
            if len(list_stack_temp) < k:
                list_stack_temp.append([(x[i], y[i]), length])
                print("临时栈中多了一组数据,目前有" + str(len(list_stack_temp)) + "组数据")

            else:
                for m in list_stack_temp:
                    list_temp.append(m[1])
                    print("临时列表中有" + str(len(list_temp)) + "组数据")
                list_temp.append(length)
                list_temp.sort()
                if length != list_temp[-1]:
                    last_ = list_temp[-1]
                    for n in list_stack_temp:
                        if n[1] == last_:
                            list_stack_temp.remove(n)
                        else:
                            continue
                    list_stack_temp.append([(x[i], y[i]), length])
                else:
                    continue
        else:
            continue
    return list_stack_temp

list1 = Find_Recent(x_discrete, y_discrete, x_discrete[43], y_discrete[43], 6)
    x_ = []
    y_ = []
    for i in list1:
        x_.append(i[0][0])
        y_.append(i[0][1])
    plt.scatter(x_discrete, y_discrete, c='y')
    plt.scatter(x_discrete[43], y_discrete[43], c='b')
    plt.scatter(x_, y_, c='r')

    plt.show()

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用Python实现K中心算法并可视化的示例代码。假设我们的数据集是一个CSV文件,每行包含两个数值,代表二维空间中的一个点。 ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt # 读取CSV文件,返回一个二维数组 def read_csv_file(file_path): data = pd.read_csv(file_path, header=None) return data.values # 计算两之间的欧几里得距离 def euclidean_distance(x1, y1, x2, y2): return np.sqrt((x1-x2)**2 + (y1-y2)**2) # 寻找距离最远的作为新的中心 def find_furthest_point(points, centers): max_distance = 0 furthest_point = None for point in points: min_distance = np.inf for center in centers: distance = euclidean_distance(point[0], point[1], center[0], center[1]) if distance < min_distance: min_distance = distance if min_distance > max_distance: max_distance = min_distance furthest_point = point return furthest_point # K中心算法 def k_center(points, k): # 随机选择一个点作为第一个中心 centers = [points[np.random.randint(0, len(points))]] while len(centers) < k: # 找到距离最远的作为新的中心 furthest_point = find_furthest_point(points, centers) centers.append(furthest_point) # 将每个点归为距离最小的中心所在的簇中 clusters = [[] for _ in range(k)] for point in points: min_distance = np.inf min_index = None for i, center in enumerate(centers): distance = euclidean_distance(point[0], point[1], center[0], center[1]) if distance < min_distance: min_distance = distance min_index = i clusters[min_index].append(point) return centers, clusters # 可视化结果 def plot_result(centers, clusters): colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k'] for i, cluster in enumerate(clusters): color = colors[i%len(colors)] for point in cluster: plt.scatter(point[0], point[1], c=color) center = centers[i] plt.scatter(center[0], center[1], marker='*', s=200, c=color) plt.show() # 读取CSV文件,运行K中心算法,绘制可视化结果 file_path = 'data.csv' points = read_csv_file(file_path) k = 3 centers, clusters = k_center(points, k) plot_result(centers, clusters) ``` 这段代码中,`read_csv_file`函数用于读取CSV文件,`euclidean_distance`函数用于计算两之间的欧几里得距离,`find_furthest_point`函数用于寻找距离最远的作为新的中心,`k_center`函数是K中心算法的实现,`plot_result`函数用于将结果可视化。在最后,我们读取CSV文件,运行K中心算法,绘制可视化结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值