聚类算法(二)
-
查看
-
案例1
import sklearn.cluster as sc import numpy as np import matplotlib.pyplot as mp import sklearn.metrics as sm # 读取样本 x = np.loadtxt('.\perf.txt', delimiter=',') # 自定义一组半径,使用轮廓系数得到最优半径 rs = np.linspace(0.3, 1.2, 10) models, scores = np.array([]), np.array([]) # 查看给的这个区间的半径 得分。 for r in rs: # 半径为r 最小样本数量为5 print("半径取值 ", r) model = sc.DBSCAN(eps=r, min_samples=5) model.fit(x) pred_y = model.labels_ score = sm.silhouette_score(x, pred_y, sample_size=len(x), metric='euclidean') models = np.append(models, model) scores = np.append(scores, score) # 10个模型存到两个列表 拿到最优得分。 # 最优模型... best_index = scores.argmax() # 最优半径 print(rs[best_index], "最优半径") # 最优得分 print(scores[best_index], "最优得分") # 最优模型 best_model = models[best_index] # 只拿到核心样本 labels = best_model.labels_ print("几个标签", labels) # 核心样本附属 拿到核心样本的下标 。 core_indices_mask = best_model.core_sample_indices_ # 拿到孤立样本 孤立样本的标签等于-1 offset_mask = labels == -1 # 绘制核心样本 # 绘制图像 mp.figure('DBSCAN', facecolor='lightgray') mp.title('DBSCAN', fontsize=16) mp.scatter(x[:,0][offset_mask], x[:,1][offset_mask], color='gray', marker='D', alpha=0.5,label='Offset Samples', s=100 ) mp.scatter(x[core_indices_mask][:,0], x[core_indices_mask][:,1], c=labels[core_indices_mask], cmap='jet', label='核心样本才是我们要关注的样本,孤立样本和外周样本去掉Core Samples', s=80) p_mask= ~(offset_mask) mp.scatter(x[p_mask][:,0], x[p_mask][:,1], c=labels[p_mask], cmap='jet', label='外周样本', alpha=0.8,s=80 ,marker='*') mp.rcParams['font.sans-serif']=['SimHei'] mp.rcParams['axes.unicode_minus'] = False mp.legend() mp.show()
查看详情
- 控制台打印
半径取值 0.3 半径取值 0.39999999999999997 半径取值 0.5 半径取值 0.6 半径取值 0.7 半径取值 0.7999999999999999 半径取值 0.8999999999999999 半径取值 1.0 半径取值 1.0999999999999999 半径取值 1.2 0.7999999999999999 最优半径 0.6366395861050828 最优得分 几个标签 [ 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 -1 1 2 3 4 0 1 2 3 4 0 0 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 0 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 -1 3 -1 0 1 -1 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]
- 输出
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术