自然语言处理实验—用K-means的方法对样本特征分类(含python代码和详细例子解释)
2021/11/15 22:09:37
本文主要是介绍自然语言处理实验—用K-means的方法对样本特征分类(含python代码和详细例子解释),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
自然语言处理实验—用K-means的方法对样本特征分类
一、算法简述
本次博客我们介绍一下机器学习里经典的聚类算法K-means,它属于典型的无监督学习算法。其核心思想也非常的简单,大致思路如下:
- 要选取 K ( K = 1 , 2 , . . ) K(K=1,2,..) K(K=1,2,..)个簇的质心,这决定了我们最终聚类的簇(每一类被分为一个簇)。
- 对每一个待分类的样本,我们都计算该样本到每个簇质心的距离,然后将该样本归类到最小距离的簇。
- 更新每个簇的质心,每个簇的新的质心等于所有位于该簇的样本的均值。
- 以此类推,重新归类样本,更新簇的质心。直到簇的质心不再改变为止。
二、情景介绍
下面我们举个栗子,记录有某音乐网站6位用户点播的歌曲流派,给定用户名称和九种音乐类型的播放数量,通过K-means将6位用户分成3簇(把播放数量当成数组或者向量进行簇质心的迭代运算)
用户/项目 | 项目1 | 项目2 | 项目3 | 项目4 | 项目5 | 项目6 | 项目7 | 项目8 | 项目9 |
---|---|---|---|---|---|---|---|---|---|
用户1 | 10 | 6 | 4 | 0 | 0 | 0 | 0 | 0 | 0 |
用户2 | 0 | 0 | 0 | 8 | 9 | 0 | 0 | 0 | 0 |
用户3 | 0 | 0 | 0 | 0 | 0 | 4 | 4 | 0 | 0 |
用户4 | 0 | 0 | 0 | 9 | 6 | 0 | 0 | 2 | 0 |
用户5 | 4 | 0 | 3 | 0 | 0 | 0 | 0 | 0 | 3 |
用户6 | 0 | 0 | 1 | 0 | 0 | 8 | 0 | 0 | 0 |
三、python代码实现
import numpy as np user_item_matrix = np.array([[10,6,4,0,0,0,0,0,0], [0,0,0,8,9,0,0,0,0], [0,0,0,0,0,4,4,0,0], [0,0,0,9,6,0,0,2,0], [4,0,3,0,0,0,0,0,3], [0,0,1,0,0,8,0,0,0]]) print("初始矩阵为:") print(user_item_matrix) K1 = user_item_matrix[0] K2 = user_item_matrix[1] K3 = user_item_matrix[2] number = 0 while(1): number += 1 print(f"\n############# cluster iter :{number} #############") cluster_one = [] cluster_two = [] cluster_three = [] distance = [] for item in user_item_matrix: distance.append([np.sqrt(sum((item - K1)**2)),np.sqrt(sum((item - K2)**2)),np.sqrt(sum((item - K3)**2))]) distance = np.array(distance) print("compute distance result\n",distance) num = distance.argmin(axis=1) print("cluster result\n",num) for i in range(len(num)): if(num[i]==0): cluster_one.append(i) elif(num[i]==1): cluster_two.append(i) else: cluster_three.append(i) K1_new = np.mean([user_item_matrix[i] for i in cluster_one ]) K2_new = np.mean([user_item_matrix[i] for i in cluster_two ]) K3_new = np.mean([user_item_matrix[i] for i in cluster_three ]) if(K1_new.all()==K1.all() and K2_new.all()==K2.all() and K3_new.all()==K3.all()): print("\n################ cluster result ################") print("cluster_one",cluster_one) print("cluster_two",cluster_two) print("cluster_three",cluster_three) break else: K1 = np.mean([user_item_matrix[i] for i in cluster_one]) K2 = np.mean([user_item_matrix[i] for i in cluster_two]) K3 = np.mean([user_item_matrix[i] for i in cluster_three])
这篇关于自然语言处理实验—用K-means的方法对样本特征分类(含python代码和详细例子解释)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04Python外包有哪些常见的主要库-icode9专业技术文章分享
- 2024-10-02基于深度学习的钢铁缺陷检测系统(yolov8、注意力机制、PyQt5界面、Python)
- 2024-10-01怎么用python搭建一个系统-icode9专业技术文章分享
- 2024-09-30Python基础入门教程
- 2024-09-30获取参数学习:Python中的基础教程
- 2024-09-30Python编程基础详解
- 2024-09-29点击加载学习:Python编程基础教程
- 2024-09-29数据科学五大Python前端库:第二部分
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础