---
title: "sklearn聚类之kmeans以及增量聚类"
author: "strayly"
date: "2019-07-11T14:47:50Z"
tags: []
categories: ["编程语言"]
slug: "sklearn-kmeans"
draft: false
lastmod: "2019-07-11T15:01:02Z"
id: 2442588
url: "https://strayly.iteye.com/blog/2442588"
---

使用kmeans聚类时，计算量往往都比较大，当有新的数据要添加到现有类别时，怎么做呢
使用sklearn简单做法就是训练时把模型保存，增量时加载模型，用predict预测就好了。
前提条件是新数据和训练时的属性数量要一致，比如在训练时使用的分词idf，把所有分词idf的词典保存下来，对于新的增量数据，调用该词典。

```python

#聚类类别数
k_num = 50
mydatas = [] #加载数据,每一条数据的分词用空格隔开，类似：[['aa bb'],['cc dd'],['ee ff']] 

idf_ret_file = "idf_ret.pkl"
if os.path.exists(idf_ret_file):
    input = open(idf_ret_file, 'rb')
    idf_ret = pickle.load(input)
    input.close()
else:
    idf_ret = cal_idf(mydatas) #计算tf-idf
    output = open(idf_ret_file, 'wb')
    #训练时把所有分词及idf值写入文件保存，以便在增量时调用
    pickle.dump(idf_ret, output) 
    output.close()

#计算数据的tf-idf值
tfidf_ret = cal_tfidf(mydatas,idf_ret)

doc_rows = len(mydatas) #数据条数
word_rows = len(idf_ret) #分词个数


#把每条数据每个分词的词频 转换成 矩阵[数据条数,分词数]
X = np.zeros([doc_rows,word_rows])
for i in range(doc_rows):
    j = 0
    for k,v in idf_ret.items():
    X[i][j] = tfidf_ret[i][k]
    j=j+1
X = np.array(X)

#模型文件
cl_file = "kmeans.pkl"
if os.path.exists(cl_file):
    input = open(cl_file, 'rb')
    cl = pickle.load(input)
    input.close()
else:
    cl = KMeans(n_clusters=k_num, init='k-means++', random_state=30, n_init=1,verbose=False)
    cl.fit(X)
    #把模型文件保存，增量时使用
    output = open(cl_file, 'wb')
    pickle.dump(cl, output)
    output.close()
#聚类结果
result = cl.predict(X)
#print(cl.cluster_centers_)
print(result)
exit()

```