输入数据集看起来像这样:
{"666": ["abc", "xyz"], "888": ["xxxo", "xxxo"], "007": ["abc"]}
我们从创建词袋模型开始,使用以下函数:
def associate_terms_with_user(unique_term_set, all_users_terms_dict): associated_value_return_dict = {} # 考虑第一个用户 for user_id in all_users_terms_dict: # 这个用户可能使用了哪些词 this_user_zero_vector = [] # 这部分可以进行某种重构 for term in unique_term_set: this_user_zero_vector.extend('0') # 这个用户实际使用了哪些词 terms_belong_to_this_user = all_users_terms_dict.get(user_id) # 让我们开始计算这个用户个人词列表中的每个词可能对应的所有可能词... global_term_element_index = 0 # 当这个词在所有可能词的范围内时 while global_term_element_index < len(unique_term_set): # 开始计算他使用的词的数量 local_term_set_item_index = 0 # 如果他使用的这个词仍在这个词范围内,一一计数 while local_term_set_item_index < len(terms_belong_to_this_user): # 如果这个用户词与这个全局词相同 if list(unique_term_set)[global_term_element_index] == terms_belong_to_this_user[local_term_set_item_index]: # 增加这个用户使用这个词的次数 this_user_zero_vector[global_term_element_index] = '1' # 转到这个用户的下一个词 local_term_set_item_index += 1 # 转到全局所有可能词列表的下一个词 global_term_element_index += 1 associated_value_return_dict.update({user_id: this_user_zero_vector}) pprint.pprint(associated_value_return_dict)
程序的输出看起来像这样:
{'007': ['0', '0', '1'], '666': ['0', '1', '1'], '888': ['1', '0', '0']}
我们如何实现一个简单的函数来根据这些向量之间的相似性对其进行聚类呢?我设想使用k-means算法,并可能使用scikit-learn库。
我之前从未做过这种事情,我不知道如何做,我对机器学习领域还是新手,我甚至不知道从哪里开始。
最后,666
和007
可能会被聚类在一起,而888
可能会单独在一个聚类中,对吗?
完整的代码在这里:链接。
回答:
Kmeans是一个好主意。
来自网络的一些示例和代码:
1) 使用Python进行文档聚类 链接
2) 使用scikit-learn的kmeans在Python中聚类文本文档 链接
3) 将长字符串列表(单词)聚类成相似性组 链接
4) Kaggle帖子 链接