使用 NVIDIA Blackwell 和 GPU 加速端点构建 DeepSeek V4
2026/5/9 2:46:30
importnumpyasnpimportmatplotlib.pyplotaspltfromscipy.cluster.hierarchyimportlinkage,dendrogram,fcluster# 1. 定义距离矩阵# 输入的5×5距离矩阵(样本0-4)distance_matrix=np.array([[0,7,2,9,3],[7,0,5,4,6],[2,5,0,8,1],[9,4,8,0,5],[3,6,1,5,0]])# 2. 生成层次聚类的"链接矩阵"(凝聚式,基于距离矩阵)fromscipy.spatial.distanceimportsquareform condensed_dist=squareform(distance_matrix)# 执行凝聚式层次聚类(方法:平均链接,也可选single/complete等)linkage_matrix=linkage(condensed_dist,method='average')# method可选:single/complete/averageplt.figure(figsize=(8,5))dendrogram(linkage_matrix,labels=[f"样本{i}"foriinrange(5)],# 样本标签leaf_rotation=0,# 标签旋转角度leaf_font_size=12,color_threshold=3,# 聚类颜色阈值(可调整)above_threshold_color='gray')plt.title('层次聚类树状图(平均链接)')plt.xlabel('样本')plt.ylabel('距离')plt.tight_layout()plt.show()# 4. 从层次聚类中提取指定簇数的聚类结果n_clusters=2# 目标簇数clusters=fcluster(linkage_matrix,t=n_clusters,criterion='maxclust')print(f"各样本的聚类结果(簇数={n_clusters}):")foriinrange(5):print(f"样本{i}→ 簇{clusters[i]}")
总的来说,K均值的和核心优点:
缺点有:
importnumpyasnpfromsklearn.clusterimportKMeansimportmatplotlib.pyplotasplt X=np.array([[0,2],# 样本0(作为第一个初始簇中心)[0,0],# 样本1(作为第二个初始簇中心)[1,0],# 样本2[5,0],# 样本3[5,2]# 样本4])sample_labels=[f"样本{i}"foriinrange(5)]# 样本标签# 2. 手动指定初始簇中心:前两个样本(样本0和样本1)init_centers=X[:2]# 取前两个样本作为初始中心print("=== 手动指定的初始簇中心 ===")print(f"初始中心1(样本1):{init_centers[0]}")print(f"初始中心2(样本2):{init_centers[1]}")# 3. 初始化并训练K-Means模型(指定初始中心)kmeans=KMeans(n_clusters=2,# 簇数固定为2(匹配初始中心数量)init=init_centers,# 手动指定初始簇中心(核心修改点)n_init=1,# 仅运行1次(因为手动指定了初始中心,无需多次初始化)random_state=42# 固定随机种子,结果可复现)y_pred=kmeans.fit_predict(X)# 拟合数据并预测簇标签# 4. 输出核心结果print("\n=== K均值聚类最终结果 ===")print(f"最终簇中心:\n{kmeans.cluster_centers_}")print(f"簇内平方和(SSE):{kmeans.inertia_:.2f}")# 评估簇内紧凑度print("\n各样本的簇分配:")forsample,labelinzip(sample_labels,y_pred):print(f"{sample}→ 簇{label}")# 5. 可视化聚类过程与结果(含初始中心+最终中心)plt.figure(figsize=(10,7))# 绘制所有样本点scatter=plt.scatter(X[:,0],X[:,1],c=y_pred,s=120,cmap='viridis',alpha=0.8,edgecolors='black')# 绘制初始簇中心(蓝色三角形,区分最终中心)plt.scatter(init_centers[:,0],init_centers[:,1],c='blue',s=300,marker='^',label='初始中心(样本0/1)',edgecolors='black')# 绘制最终簇中心(红色星号)plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],c='red',s=300,marker='*',label='最终簇中心',edgecolors='black')# 标注每个样本的编号fori,sampleinenumerate(sample_labels):plt.text(X[i,0]+0.1,X[i,1]+0.1,sample,fontsize=12,fontweight='bold')# 图表美化plt.xlabel('特征1',fontsize=12)plt.ylabel('特征2',fontsize=12)plt.title('K均值聚类结果(初始中心为前两个样本)',fontsize=14)plt.grid(alpha=0.3)# 网格线增强可读性plt.legend(loc='upper right')plt.axis('equal')# 等比例坐标轴,避免视觉变形plt.tight_layout()plt.show()在这里插入代码片
这里的样本0和样本4对应书中的样本1和样本5