Python教程

自然语言处理实验—用K-means的方法对样本特征分类(含python代码和详细例子解释)

本文主要是介绍自然语言处理实验—用K-means的方法对样本特征分类(含python代码和详细例子解释),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

自然语言处理实验—用K-means的方法对样本特征分类

一、算法简述

本次博客我们介绍一下机器学习里经典的聚类算法K-means,它属于典型的无监督学习算法。其核心思想也非常的简单,大致思路如下:

  1. 要选取 K ( K = 1 , 2 , . . ) K(K=1,2,..) K(K=1,2,..)个簇的质心,这决定了我们最终聚类的簇(每一类被分为一个簇)。
  2. 对每一个待分类的样本,我们都计算该样本到每个簇质心的距离,然后将该样本归类到最小距离的簇。
  3. 更新每个簇的质心,每个簇的新的质心等于所有位于该簇的样本的均值。
  4. 以此类推,重新归类样本,更新簇的质心。直到簇的质心不再改变为止。

二、情景介绍

下面我们举个栗子,记录有某音乐网站6位用户点播的歌曲流派,给定用户名称和九种音乐类型的播放数量,通过K-means将6位用户分成3簇(把播放数量当成数组或者向量进行簇质心的迭代运算)

用户/项目项目1项目2项目3项目4项目5项目6项目7项目8项目9
用户11064000000
用户2000890000
用户3000004400
用户4000960020
用户5403000003
用户6001008000

三、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代码和详细例子解释)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!