【563】DBSCAN通过地理距离实现
提前计算好地理距离矩阵,然后将函数名复制到DBSCAN的函数里面。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | import pandas as pd import numpy as np import folium from scipy.spatial import ConvexHull from math import radians, cos, sin, asin, sqrt from sklearn.cluster import DBSCAN def geodistance(lon1, lat1, lon2, lat2): # 经度1,纬度1,经度2,纬度2 (十进制度数) """ 大圆距离,great_circle Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # 将十进制度数转化为弧度 lon1, lat1, lon2, lat2 = map (radians, [lon1, lat1, lon2, lat2]) # haversine公式 dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2 ) * * 2 + cos(lat1) * cos(lat2) * sin(dlon / 2 ) * * 2 c = 2 * asin(sqrt(a)) r = 6371 # 地球平均半径,单位为公里 return c * r * 1000 def get_distance_matrix_from_array(points_array): """ 构建距离矩阵,每个点之间的 great_circle 距离 """ num = len (points_array) distance_matrix = np.zeros((num, num)) for i in range (num): for j in range (num): if i = = j: continue lng1, lat1 = points_array[i] lng2, lat2 = points_array[j] dis = geodistance(lng1, lat1, lng2, lat2) distance_matrix[i][j] = dis return distance_matrix def DBSCAN_pts(aoi_points, eps, minpts): """ minpts: 用数量作为计算 aoi_points: 字典 {'望京小区': [(0,1), (0,2), (1,2), (1,3)], ...} """ for aoi, pts in aoi_points.items(): distance_matrix = get_distance_matrix_from_array(pts) y_pred = DBSCAN(eps = eps, min_samples = minpts, metric = 'precomputed' ).fit_predict(distance_matrix) # y_pred 的输出结果肯定有 -1,极端情况只有 -1 # -1 的结果就是噪声点 # 对于只有 -1 的情况,认为是点比较分散,无法聚类,是要删除掉的 # 如果都为 -1,直接舍弃 if len ( set (y_pred.tolist())) = = 1 and (y_pred[ 0 ] = = - 1 ): continue # 去掉 -1 的点 tmp_pts = np.array(pts)[y_pred ! = - 1 ] y_pred = y_pred[y_pred ! = - 1 ] # 聚类点太少的簇可以删掉,初定为 5 for i in range (y_pred. max () + 1 ): if list (y_pred).count(i) < = 5 : tmp_pts = tmp_pts[y_pred ! = i] y_pred = y_pred[y_pred ! = i] aoi_points_dbscan_1[aoi] = tmp_pts.tolist() return aoi_points_dbscan_1 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)