from kmodes.kmodes import KModes
import numpy as np
import pandas as pd
import jieba
from gensim import corpora,models,similarities
data = pd.read_excel(r’G:\aas\cc.xlsx’)
data2 = pd.DataFrame(pd.read_excel(r’G:\aas\cc.xlsx’))
data1 = data[[‘类型’,‘稀缺度’,‘时间要素’,‘价值’,‘保护级别’,‘遗产类别’,‘修缮难度’,
‘保存现状’,‘完整度’,‘人口规模与分布’,‘现代文化生活需求度’]]
#print(data1)
km = KModes(n_clusters=3, init=‘Huang’, n_init=11, verbose=1)#n_clusters=10,分成10类
clusters = km.fit_predict(data1)
#print(km.cluster_centroids_)
data_df = pd.DataFrame(km.cluster_centroids_.T)#将二维列表转换成dataframe对象,然后再调用这个pandas.DataFrame.to_excel函数
data_df.columns = [‘第一类’,‘第二类’,‘第三类’]#列名
data_df.index = [‘类型’,‘稀缺度’,‘时间要素’,‘价值’,‘保护级别’,‘遗产类别’,
‘修缮难度’,‘保存现状’,‘完整度’,‘人口规模与分布’,‘现代文化生活需求度’]#行名
a = “”.join(km.cluster_centroids_[0])
b = “”.join(km.cluster_centroids_[1])
c = “”.join(km.cluster_centroids_[2])
all_doc = []
all_doc.append(a)
all_doc.append(b)
all_doc.append©
#print(all_doc)
all_doc_list = []
for doc in all_doc:
doc_list = [word for word in jieba.cut(doc)]
all_doc_list.append(doc_list)
#print(all_doc_list)#类分词完成
data2 = np.array(data2)
data2 = data2.tolist()
#print(data2)
all_yangben = []
for i in range(33):
ronghe = “”.join(data2[i])
all_yangben.append(ronghe)
yangben_list = []
for yangben in all_yangben:
yangben_test = [word for word in jieba.cut(yangben)]
yangben_list.append(yangben_test)
#print(yangben_list)
dictionary = corpora.Dictionary(all_doc_list)
dictionary.keys()
#print(dictionary.token2id)
corpus = [dictionary.doc2bow(doc) for doc in all_doc_list]#以下使用doc2bow制作语料库
#print(corpus)
corpus_yangben = [dictionary.doc2bow(yangben) for yangben in yangben_list]
#print(corpus_yangben)
tfidf = models.TfidfModel(corpus)#使用TF-IDF模型对语料库建模
index = similarities.SparseMatrixSimilarity(tfidf[corpus], num_features=len(dictionary.keys()))
lei_1 = []
lei_2 = []
lei_3 = []
for i in range(33):
sim = index[tfidf[corpus_yangben[i]]]
#print(sim)
paixu = sorted(enumerate(sim), key=lambda item: -item[1])#根据相似度排序
if paixu[0][0] == 0:
lei_1.append(data2[i][0])
elif paixu[0][0] == 1:
lei_2.append(data2[i][0])
elif paixu[0][0] == 2:
lei_3.append(data2[i][0])
data_2 = [lei_1,lei_2,lei_3]
#print(data_2)
writer = pd.ExcelWriter(‘实验.xlsx’)#命名
data_df.to_excel(writer,float_format=’%.5f’,sheet_name=‘聚类’)#导出
ddd = pd.DataFrame(data_2)
ddd.index = [‘第一类’,‘第二类’,‘第三类’]#列名
ddd.to_excel(writer,float_format=’%.5f’,sheet_name=‘划分’)#导出
writer.save()#保存
输入一个文件,聚类并分类
最新推荐文章于 2024-03-09 12:45:37 发布